Skip to content

Instantly share code, notes, and snippets.

@GGist
Last active August 29, 2015 14:21
Show Gist options
  • Save GGist/99f33cdf3e281afd81ad to your computer and use it in GitHub Desktop.
Save GGist/99f33cdf3e281afd81ad to your computer and use it in GitHub Desktop.
Multicast On Multiple Interfaces
#define WIN32_LEAN_AND_MEAN
#include <winsock2.h>
#include <Ws2tcpip.h>
#include <mswsock.h>
#include <stdio.h>
int main() {
WSADATA wsaData;
char opt;
int err;
err = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (err != 0) {
printf("WSAStartup failed with the error: %d\n", err);
return -1;
}
// Create The Socket
SOCKET sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
// Set REUSEADDR Socket Option
opt = TRUE;
err = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
if (err != 0) {
printf("setsockopt failed with the error: %d\n", err);
return -1;
}
// Subscribe To Multicast
struct ip_mreq mcast_addr;
mcast_addr.imr_multiaddr.s_addr = inet_addr("239.255.255.250");
mcast_addr.imr_interface.s_addr = inet_addr("10.0.1.4");
err = setsockopt(sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char *) &mcast_addr, sizeof(struct ip_mreq));
if (err != 0) {
printf("setsockopt failed with the error: %d\n", err);
return -1;
}
mcast_addr.imr_interface.s_addr = inet_addr("192.168.1.105");
err = setsockopt(sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char *) &mcast_addr, sizeof(struct ip_mreq));
if (err != 0) {
printf("setsockopt failed with the error: %d\n", err);
return -1;
}
mcast_addr.imr_interface.s_addr = inet_addr("127.0.0.1");
err = setsockopt(sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char *) &mcast_addr, sizeof(struct ip_mreq));
if (err != 0) {
printf("setsockopt failed with the error: %d\n", err);
return -1;
}
// Bind Socket
struct sockaddr_in local_addr;
local_addr.sin_family = AF_INET;
local_addr.sin_addr.s_addr = htonl(INADDR_ANY);
local_addr.sin_port = htons(1900);
err = bind(sock, (SOCKADDR*) &local_addr, sizeof(local_addr));
if (err != 0) {
printf("bind failed with the error: %d\n", err);
return -1;
}
// Listen For Data
char recv_buff[500];
int recv_len = sizeof(recv_buff), result = 0;
while (1) {
result = recv(sock, recv_buff, recv_len, 0);
if (result > 0) {
printf("Received %d Bytes\n", result);
int i;
for (i = 0; i < result; ++i) {
printf("%c", recv_buff[i]);
}
} else {
printf("Err Connection: %d\n", result);
return -1;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment