The following test program shows how to set the TTL for Multicast packets. For this it is needed to control the stack through the datagram socket. Setting the TTL cannot be done on the transmitting socket/interface directly. To use this example, the addresses used need to be edited to the local environment.
/**
* Demonstration of how to set TTL on a multicast socket
**/
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
struct in_addr localInterface;
struct sockaddr_in groupSock;
int sd;
int datalen;
char databuf[1024];
int main( int argc, char *argv[] )
{
// Open the datagram socket for the control stream
sd = socket( AF_INET, SOCK_DGRAM, 0 );
if( sd < 0 ) {
perror( "opening datagram socket" );
exit( 1 );
}
// Get the local interface and mark it as multicast interface
localInterface.s_addr = inet_addr( "192.168.12.240" );
if( setsockopt
( sd, IPPROTO_IP, IP_MULTICAST_IF, ( char * ) &localInterface,
sizeof( localInterface ) ) < 0 ) {
perror( "setting local interface multicast" );
exit( 1 );
}
// Now set the TTL
// In this case to 31
{
unsigned char ttl;
ttl = 31;
// Write TTL for IP Multicasrt packets into the control socket
if( setsockopt
( sd, IPPROTO_IP, IP_MULTICAST_TTL, ( void * ) &ttl,
sizeof( ttl ) ) < 0 ) {
perror( "setting TTL on local interface" );
exit( 1 );
}
}
// Do a testsend on the socket so one can validate the packets
datalen = 10;
if( sendto
( sd, databuf, datalen, 0, ( struct sockaddr * ) &groupSock,
sizeof( groupSock ) ) < 0 ) {
perror( "sending datagram message" );
}
}
Related Attachments
None Found
Please contact us with your questions or concerns.