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)
- Create a socket
- Fill in information about the interface you will use
- Bind the socket to the interface
- Fill in information about the multicast group you will use
- Send the data
This line creates a UDP connectionless socket
fd = socket( AF_INET, SOCK_DGRAM, 0 ) ;
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 ) ;
This line binds the interface address/port number to the socket that was just created.
bind( fd, (struct sockaddr*) &if_addr, sizeof( if_addr ) ) ;
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 ) ;
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 ) ) ;
msg,
sizeof( msg ),
0,
(struct sockaddr *) &mc_addr,
sizeof( mc_addr ) ) ;
(udp_listener.cxx - see the link above)
- Create a socket
- Fill in information about the interface you will use
- Bind the socket to the interface
- Request to join the multicast group
- Receive data
Create a UDP connectionless socket...add non-blocking reads
fd = socket( AF_INET, SOCK_DGRAM | SOCK_NONBLOCK, 0 ) ;
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 ) ;
Bind the socket to the 'interface'
bind( fd, (struct sockaddr *) &if_addr, sizeof( if_addr ) ) ;
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 ) ) ;
The recvfrom() function will read multicast data off the socket.
recv_bytes = recvfrom( fd,
msgbuf,
MSGBUFSIZE,
0,
(struct sockaddr *) &if_addr,
(socklen_t *) &addrlen ) ;
msgbuf,
MSGBUFSIZE,
0,
(struct sockaddr *) &if_addr,
(socklen_t *) &addrlen ) ;
No comments:
Post a Comment