Last active
August 29, 2015 14:26
-
-
Save elvinio/6bdc2ad1f1a509e5e050 to your computer and use it in GitHub Desktop.
Example program on how to use standard C network library to subscribe to a multicast server.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <netdb.h> | |
#include <arpa/inet.h> | |
#include <netinet/tcp.h> | |
#include <sys/socket.h> | |
#define BUFFERSIZE 2048 | |
int main(){ | |
int sockDesc = 0; | |
if ((sockDesc = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) { | |
std::cout << "Socket creation failed\n"; | |
return 0; | |
} | |
int32_t port = 12911; | |
std::string ip = "237.0.0.11"; | |
struct ip_mreq multicastRequest; | |
multicastRequest.imr_multiaddr.s_addr = inet_addr(ip.c_str()); | |
multicastRequest.imr_interface.s_addr = htonl(INADDR_ANY); | |
if (setsockopt(sockDesc, IPPROTO_IP, IP_ADD_MEMBERSHIP, (void *) &multicastRequest, | |
sizeof(multicastRequest)) < 0) { | |
std::cout << "Failed to join multicast group\n"; | |
return; | |
} | |
// If you want the socket to be non-blocking, set the timeout. | |
// It is set to 5 seconds here. | |
struct timeval tv; | |
tv.tv_sec = 5; | |
tv.tv_usec = 0; | |
setsockopt(sockDesc, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv,sizeof(struct timeval)); | |
char buffer[BUFFERSIZE]; | |
while(true){ | |
if ((bytesRead = recvfrom(sockDesc, (void *) buffer, BUFFERSIZE, 0, NULL, NULL)) < 0) { | |
if(errno != 11){ | |
std::cout << "Socket read " << bytesRead << " errno " << errno << ". Closing.\n"; | |
return; | |
} | |
continue; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment