Skip to content

Instantly share code, notes, and snippets.

@heatblazer
Created March 7, 2018 15:12
Show Gist options
  • Save heatblazer/c97b7a885354a0bcbca4c509967a4ba0 to your computer and use it in GitHub Desktop.
Save heatblazer/c97b7a885354a0bcbca4c509967a4ba0 to your computer and use it in GitHub Desktop.
Multicast example for WSA
#include "stdafx.h"
#include "resolve.h"
#include <WinSock2.h>
#include <WS2tcpip.h>
#include <MSWSock.h>
#pragma comment (lib, "Ws2_32.lib")
#define MAX_LEN 256
struct MyApp
{
struct
{
int argc;
char** argv;
} m_args;
SOCKET m_socketFd;
int m_sockOptFlag;
struct sockaddr_in m_macaddr;
struct
{
char data[MAX_LEN + 1];
int len;
} m_recvString;
struct ip_mreq m_req;
char m_mcaddr_str[64];
unsigned int m_port;
struct sockaddr_in m_fromAddress;
int m_fromLen;
WSADATA m_wsa;
public:
explicit MyApp(int argc, char** argv)
: m_args({argc, argv})
{
memset(m_mcaddr_str, 0, sizeof(m_mcaddr_str));
strcat_s(m_mcaddr_str, "224.1.50.15");
m_port = 1234;
}
~MyApp()
{
if ((setsockopt(m_socketFd, IPPROTO_IP, IP_DROP_MEMBERSHIP,
(char*)&m_req, sizeof(m_req))) < 0)
{
perror("setsockopt() failed");
}
closesocket(m_socketFd);
WSACleanup();
}
bool init()
{
bool res = false;
if (WSAStartup(MAKEWORD(2, 0), &m_wsa) != 0)
{
fprintf(stderr, "Failed to load WSA\n");
return res;
}
if ( (m_socketFd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
{
perror("socket() failed");
printf("Last error (%d)\n" , WSAGetLastError());
return res;
}
if ((setsockopt(m_socketFd, SOL_SOCKET, SO_REUSEADDR, (char*)&m_sockOptFlag,
sizeof(m_sockOptFlag)) ) < 0)
{
perror("setsockopt() failed");
return res;
}
memset(&m_macaddr, 0, sizeof(m_macaddr));
m_macaddr.sin_family = AF_INET;
m_macaddr.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
m_macaddr.sin_port = htons(m_port);
{
res = true;
}
return res;
}
bool bind()
{
bool res = false;
if (::bind(m_socketFd, (struct sockaddr*) &m_macaddr, sizeof(m_macaddr)) < 0)
{
perror("bind() failed");
return res;
}
if (inet_pton(AF_INET, m_mcaddr_str, &m_req.imr_multiaddr.S_un.S_addr) <=0)
{
perror("inet_pton() failed with error");
return res;
}
m_req.imr_interface.S_un.S_addr = htonl(INADDR_ANY);
if (setsockopt(m_socketFd, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char*)&m_req, sizeof(m_req)) < 0)
{
perror("setsockopt() failed");
printf("Last error(%d)\n", WSAGetLastError());
return res;
}
int recv_len = 0;
res = true;
for (;;)
{
memset(m_recvString.data, 0, sizeof(m_recvString));
m_fromLen = sizeof(m_fromAddress);
memset(&m_fromAddress, 0, m_fromLen);
if ((recv_len = recvfrom(m_socketFd, m_recvString.data, MAX_LEN, 0,
(struct sockaddr*)&m_fromAddress, &m_fromLen)) < 0)
{
perror("recvfrom() failed");
res = false;
break;
}
printf("Received %d bytes\n");
printf("%s\n", m_recvString.data);
}
return res;
}
};
int __cdecl main(int argc, char** argv)
{
MyApp app(argc, argv);
if (app.init())
app.bind();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment