/* Initialize the group sockaddr structure with a group address and port. */ memset((char *) &groupSock, 0, sizeof(groupSock)); groupSock.sin_family = AF_INET; groupSock.sin_addr.s_addr = inet_addr(UDP_MULTICAST_ADDR); groupSock.sin_port = htons(UDP_MULTICAST_PORT);
/* setting loopback, to control wether you do not receive your own datagrams or not.*/ char loopch = CONFIG_MULTICAST_LOOP_EN; if(setsockopt(sd, IPPROTO_IP, IP_MULTICAST_LOOP, (char *)&loopch, sizeof(loopch)) < 0) { perror("Setting IP_MULTICAST_LOOP error"); close(sd); exit(1); } else { printf("Disabling the loopback...OK.\n"); }
/* Set local interface for outbound multicast datagrams. */ /* The IP address specified must be associated with a local, */ /* multicast capable interface. */ localInterface.s_addr = inet_addr(UDP_LOCAL_ADDR); if(setsockopt(sd, IPPROTO_IP, IP_MULTICAST_IF, (char *)&localInterface, sizeof(localInterface)) < 0) { perror("Setting local interface error"); exit(1); } else { printf("Setting the local interface...OK\n"); }
/* Send a message to the multicast group specified by the groupSock sockaddr structure. */ if(sendto(sd, databuf, datalen, 0, (struct sockaddr*)&groupSock, sizeof(groupSock)) < 0) { perror("Sending datagram message error"); } else { printf("Sending datagram message...OK\n"); }
/* Try the re-read from the socket if the loopback is not disable*/ #if CONFIG_MULTICAST_LOOP_EN memset(databuf, 0, sizeof(databuf)); if(read(sd, databuf, datalen) < 0) { perror("Reading datagram message error\n"); close(sd); exit(1);
} else { printf("Reading datagram message from client...OK\n"); printf("The message is: %s\n", databuf); } #endif return0; }
intmain(int argc, char *argv[]) { /* Create a datagram socket on which to receive. */ sd = socket(AF_INET, SOCK_DGRAM, 0); if(sd < 0) { perror("Opening datagram socket error"); exit(1); } else { printf("Opening datagram socket....OK.\n"); }
/* Enable SO_REUSEADDR to allow multiple instances of this application to receive copies of the multicast datagrams. */ #if CONFIG_ADDRESS_REUSER_EN int reuse = 1; if(setsockopt(sd, SOL_SOCKET, SO_REUSEADDR, (char *)&reuse, sizeof(reuse)) < 0) { perror("Setting SO_REUSEADDR error"); close(sd); exit(1); } else { printf("Setting SO_REUSEADDR...OK.\n"); } #endif
/* Bind to the proper port number with the IP address */ /* specified as INADDR_ANY. */ memset((char *) &localSock, 0, sizeof(localSock)); localSock.sin_family = AF_INET; localSock.sin_port = htons(UDP_MULTICAST_PORT); localSock.sin_addr.s_addr = INADDR_ANY;
/* Join the multicast group 226.1.1.1 on the local 203.106.93.94 */ /* interface. Note that this IP_ADD_MEMBERSHIP option must be */ /* called for each local interface over which the multicast */ /* datagrams are to be received. */ group.imr_multiaddr.s_addr = inet_addr(UDP_MULTICAST_ADDR); group.imr_interface.s_addr = inet_addr(UDP_LOCAL_ADDR);