//------------------------------------------------------------------- // multirecv.cpp // // This application joins a IP-multicast group and displays all // the group messages it receives on the standard output device // until the user terminates the program by typing -C. // // to compile: $ g++ multirecv.cpp -o multirecv // to execute: $ ./multirecv // // NOTE: Adapted from the online example by Antony Courtney and // Frederic Bastien, posted at Trinity College, Dublin, Ireland // . // // programmer: ALLAN CRUSE // written on: 19 MAR 2009 //------------------------------------------------------------------- #include // for printf(), perror() #include // for exit() #include // for htons(), socket() #define HELLO_PORT 54321 #define HELLO_GROUP "224.3.3.6" #define MSGBUFSIZE 256 int main( int argc, char **argv ) { //------------------------------------------------ // setup our destination socket-address structure //------------------------------------------------ struct sockaddr_in saddr = { 0 }; saddr.sin_family = AF_INET; saddr.sin_port = htons( HELLO_PORT ); saddr.sin_addr.s_addr = htonl( INADDR_ANY ); //------------------------------------------------ // we open what looks like an ordinary UDP socket //------------------------------------------------ int sock = socket( AF_INET, SOCK_DGRAM, IPPROTO_UDP ); if ( sock < 0 ) { perror( "socket" ); exit(1); } //------------------------------------------------ // we allow multiple sockets to use the same port //------------------------------------------------ unsigned int yes = 1; int ysiz = sizeof( yes ); if ( setsockopt( sock, SOL_SOCKET, SO_REUSEADDR, &yes, ysiz ) < 0 ) { perror( "setsockopt REUSEADDR" ); exit(1); } //----------------------------------------- // bind our socket to this receive address //----------------------------------------- if ( bind( sock, (sockaddr*)&saddr, sizeof( saddr ) ) < 0 ) { perror( "bind" ); exit(1); } //---------------------------------------------------- // we use the 'setsockopt()' function to request that // the kernel 'join' our specified IP-multicast group //---------------------------------------------------- struct ip_mreq mreq = { 0 }; int msiz = sizeof( mreq ); mreq.imr_multiaddr.s_addr = inet_addr( HELLO_GROUP ); mreq.imr_interface.s_addr = htonl( INADDR_ANY ); if ( setsockopt( sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, msiz ) ) { perror( "setsockopt ADD_MEMBERSHIP" ); exit(1); } //----------------------------------------- // now we just enter a read-and-print loop //----------------------------------------- while ( 1 ) { char buf[ MSGBUFSIZE ] = { 0 }; int len = sizeof( buf ); int nbytes = recv( sock, buf, len, 0 ); if ( nbytes < 0 ) { perror( "recvfrom" ); exit(1); } puts( buf ); } }