//------------------------------------------------------------------- // multihop.cpp (Addendum to of our 'multisend.cpp' demo) // // This application will transmit a "Hello, World!" message to // its designated IP-multicast group once every second until a // user decides to conclude the program by typing -C. // // ADDENDUM: modified default multicast TTL via socket-option. // // to compile: $ g++ multihop.cpp -o multihop // to execute: $ ./multihop // // NOTE: Adapted from the online example by Antony Courtney and // Frederic Bastien, posted at Trinity College, Dublin, Ireland // . // // programmer: ALLAN CRUSE // written on: 26 MAR 2009 //------------------------------------------------------------------- #include // for printf(), perror() #include // for exit() #include // for sleep() #include // for strlen() #include // for htons(), socket() #define HELLO_PORT 54321 #define HELLO_GROUP "224.3.3.6" int main( int argc, char **argv ) { //------------------------------------------------------- // we let the user specify a value for the multicast TTL //------------------------------------------------------- int tval = ( argc > 1 ) ? atoi( argv[1] ) : 2; //------------------------------------------------ // 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 modify the default value of TTL in multicast packets //---------------------------------------------------------- int tlen = sizeof( tval ); if ( setsockopt( sock, SOL_IP, IP_MULTICAST_TTL, &tval, tlen ) < 0 ) { perror( "setsockopt" ); exit(1); } //---------------------------------------------------- // we set up the 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 = inet_addr( HELLO_GROUP ); //--------------------------------------------------------- // now we just 'sendto()' our destination once each second //--------------------------------------------------------- char message[] = "Hello, World!"; for(;;) { sleep( 1 ); if ( sendto( sock, message, sizeof( message ), 0, (sockaddr *)&saddr, sizeof( saddr ) ) < 0 ) { perror("sendto"); exit(1); } } }