Saturday, March 16, 2013

Linux UDP Multicast


Setting up a UDP multicast server/client in Linux should be pretty straightforward. An example is provided below with some comments.

Get the files hosted at https://www.cubby.com/ using the link below:
UDP sender/listener example

UDP Multicast Sender in Linux (C/C++)
(udp_sender.cxx - see the link above)
  1. Create a socket

  2. This line creates a UDP connectionless socket
    fd = socket( AF_INET, SOCK_DGRAM, 0 ) ;
     
  3. Fill in information about the interface you will use

  4. These lines fill a data structure that provide out going interface address and port number.
    if_addr.sin_family = AF_INET ; if_addr.sin_addr.s_addr = inet_addr( INTERFACE_ADDR ) ; if_addr.sin_port = htons( INTERFACE_PORT ) ;
     
  5. Bind the socket to the interface

  6. This line binds the interface address/port number to the socket that was just created.
    bind( fd, (struct sockaddr*) &if_addr, sizeof( if_addr ) ) ;
     
  7. Fill in information about the multicast group you will use

  8. Fill in another data structure that provides information about the destination multicast address and port number.
    mc_addr.sin_family = AF_INET ; mc_addr.sin_addr.s_addr = inet_addr( MULTICAST_ADDR ) ; mc_addr.sin_port = htons( MULTICAST_PORT ) ;
     
  9. Send the data

  10. The sendto() command will transmit the data out of the socket and onto the network with the multicast destination address.
    result = sendto( fd,
    msg,
    sizeof( msg ),
    0,
    (struct sockaddr *) &mc_addr,
    sizeof( mc_addr ) ) ;

UDP Multicast Listener in Linux (C/C++)
(udp_listener.cxx - see the link above)
  1. Create a socket

  2. Create a UDP connectionless socket...add non-blocking reads
    fd = socket( AF_INET, SOCK_DGRAM | SOCK_NONBLOCK, 0 ) ;

  3. Fill in information about the interface you will use

  4. In this case the listener can listen on any interface as long as the multicast port is correct.
    if_addr.sin_family = AF_INET ; if_addr.sin_addr.s_addr = htonl( INADDR_ANY ) ; if_addr.sin_port = htons( MULTICAST_PORT ) ;

  5. Bind the socket to the interface

  6. Bind the socket to the 'interface'
    bind( fd, (struct sockaddr *) &if_addr, sizeof( if_addr ) ) ;

  7. Request to join the multicast group

  8. This is the important part...here you indicate the multicast address you want to listen to and the interface that will listen for the multicast.
    mreq.imr_multiaddr.s_addr = inet_addr( MULTICAST_ADDR ) ; mreq.imr_interface.s_addr = inet_addr( INTERFACE_ADDR ) ; ret_val = setsockopt( fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof( mreq ) ) ;

  9. Receive data

  10. The recvfrom() function will read multicast data off the socket.
    recv_bytes = recvfrom( fd,
    msgbuf,
    MSGBUFSIZE,
    0,
    (struct sockaddr *) &if_addr,
    (socklen_t *) &addrlen ) ;
 

No comments:

Post a Comment