/* NAME: Multicast sender SYNOPSIS: McastSend DESCRIPTION: The program creates a datagram socket in the inet domain. It reads from stdin and sends data to a multicast. */ #include #include #include #include #include #include #include #include #include #include #include #include #define BUFSIZE 1024 char buf[BUFSIZE]; int main( int argc, char * argv[] ) { int s; struct sockaddr_in mc_group; struct sockaddr_in addr; int rc; unsigned long int GroupIP; char loop, ttl; if (argc != 3) { fprintf(stderr, "Usage : %s \n",argv[0]); exit(0); } if( (GroupIP = inet_addr(argv[1]))== -1) printf("error in inet_addr\n"); mc_group.sin_family = AF_INET; mc_group.sin_port = htons(atoi(argv[2])); mc_group.sin_addr.s_addr = GroupIP; s = socket (PF_INET,SOCK_DGRAM,0); /* By default, messages sent to the multicast group are looped back to the local host. this function disables that. loop = 1 means enable loopback loop = 0 means disable loopback NOTE : by default, loopback is enabled */ loop = 1; if( setsockopt(s,IPPROTO_IP,IP_MULTICAST_LOOP,(char *) &loop, sizeof(u_char)) == -1 ) { printf("error in setting loopback\n"); } /* set the Time-To-Live value ttl=0; data is kept within the machine. ttl=1; data is sento to the network, but it does not cross any router. ttl=2; data reaches the computer one router away. and so on. */ ttl = 1; if( setsockopt(s,IPPROTO_IP,IP_MULTICAST_TTL,(char *) &ttl, sizeof(u_char)) == -1 ) { printf("error in setting loopback value\n"); } for(;;) { printf("\nType anything followed by RETURN, or type CTRL-D to exit\n"); rc=read(0,buf, sizeof(buf)); if (rc == 0) break; buf[rc]='\0'; printf("Sending \"%s\"\n", buf); if (sendto(s, buf, rc, 0, (struct sockaddr*)&mc_group, sizeof(mc_group)) <0 ) perror("sending datagram message"); } printf ("EOF... exit\n"); close(s); }