// open UDP IPv4 socket
int mSocketFd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
// set broadcast
int broadcast = 1;
retur = setsockopt(mSocketFd, SOL_SOCKET, SO_BROADCAST, &broadcast, sizeof(broadcast));
if(retur < 0){
perror("setbroadcast failed");
return false;
}
// set reuse address
int on = 1;
retur = setsockopt(mSocketFd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
if(retur < 0){
perror("setreuse failed");
return false;
}
// set timeout
struct timeval timeout;
timeout.tv_sec = 1;
timeout.tv_usec = 0;
retur = setsockopt(mSocketFd, SOL_SOCKET, SO_RCVTIMEO,(struct timeval *)&timeout,sizeof(struct timeval));
if(retur < 0){
perror("settimeout failed");
return false;
}
// bind to broadcast
struct sockaddr_in addr;
memset(&addr,0,sizeof(addr));
addr.sin_port = htons(2054);
addr.sin_family = AF_INET;
inet_pton(AF_INET, "10.0.0.255", (void*)&addr.sin_addr);
retur = bind( mSocketFd, (struct sockaddr *)&addr, sizeof(addr) );
if(retur < 0){
perror("bind failed");
return false;
}
// connect to 10.0.0.201
memset(&addr,0,sizeof(addr));
addr.sin_port = htons(2054);
addr.sin_family = AF_INET;
inet_pton(AF_INET, "10.0.0.201", (void*)&addr.sin_addr);
retur = connect(mSocketFd, (struct sockaddr*) &addr, sizeof(addr));
if(retur < 0){
perror("connect failed");
return false;
}
// join multicast
struct ip_mreq mreq;
mreq.imr_multiaddr.s_addr = inet_addr("225.0.0.201");
mreq.imr_interface.s_addr = inet_addr("10.0.0.32"); // hardcoded for this test, but uses code to check
retur = setsockopt(mSocketFd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq));
if(retur < 0){
perror("multicast join failed");
return false;
}
char data[512];
// fill data
int ret = send(mSocketFd, data, 512,0);
if(ret == 512){
printf("UDP send success\n");
return true;
}else {
perror("UDP send failed");
return false;
}