I am new to windows socket programming. I have a device which gives udp data through a port, ipv6 protocol based. I am trying to capture this in a console application written in visual studio in Windows 7. Socket creation and bind are successful but nothing is recieved from the port specified.
I have done this in Linux since i am basically a linux system software developer and it is working perfect. Is there anything else i need to do to get UDP packets in windows. I have checked with wireshark in windows and found that the UDP packets are coming from the device to the PC.
Working Code Done in Linux:
int main()
{
struct sockaddr_in6 ipv6_addr;
int addrlen, ipv6_sockfd, cnt, err;
char response[200], cmd[500];
cJSON *param, *root;
memset(response, 0, sizeof(response));
ipv6_sockfd = socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP);
if (ipv6_sockfd < 0) {
perror("socket");
exit(1);
}
bzero((char *)&ipv6_addr, sizeof(ipv6_addr));
ipv6_addr.sin6_family = AF_INET6;
ipv6_addr.sin6_addr = in6addr_any;
ipv6_addr.sin6_port = htons(DISCOVERY_PORT);
addrlen = sizeof(ipv6_addr);
if (bind(ipv6_sockfd, (struct sockaddr *)&ipv6_addr, sizeof(ipv6_addr)) < 0) {
perror("bind");
exit(1);
}
cnt = recvfrom(ipv6_sockfd, response, sizeof(response), 0, (struct sockaddr *)&ipv6_addr, &addrlen);
if (cnt < 0) {
perror("recvfrom");
exit(1);
}
DBG("Response = \"%s\"\n", response);
close(ipv6_sockfd);
}
Code in Windows:
#include "stdafx.h"
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>
#define DISCOVERY_PORT 13006
#define DEFAULT_BUFLEN 512
#include <WinSock2.h>
#pragma comment(lib,"ws2_32.lib")
int _tmain(int argc, _TCHAR* argv[])
{
//UDP Data
int addrlen, msglen;
char message[300];
int err, opt = 1;
SOCKET s;
struct sockaddr_in6 hum, addr;
//Initializing winsock
WSADATA wsa;
err = WSAStartup(MAKEWORD(2, 2), &wsa);
if (err != 0)
{
printf("\nFailed Initializing Winsock EROR CODE : %d\n", err);
return 1;
}
//UDP Socket creation
s = socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP);
if (s == INVALID_SOCKET)
{
printf("\nUDP socket creation failed ERROR CODE : %d\n", WSAGetLastError());
closesocket(s);
WSACleanup();
return 1;
}
//UDP socket definition
memset(&hum, 0, sizeof(addr));
hum.sin6_family = AF_INET6;
hum.sin6_addr = in6addr_any;
hum.sin6_port = htons(DISCOVERY_PORT);
//UDP SOCKET Binding
if (bind(s, (sockaddr *)&hum, sizeof(hum)) == SOCKET_ERROR)
{
printf("\nUDP socket binding failed ERROR CODE : %d\n", WSAGetLastError());
closesocket(s);
WSACleanup();
return 1;
}
//UDP Receiving data
addrlen = sizeof(addr);
msglen = recvfrom(s, message, sizeof(message), 0, (struct sockaddr *)&addr, &addrlen);
if (msglen == SOCKET_ERROR)
{
printf("\nUDP Broadcast not received ERROR CODE : %d\n", WSAGetLastError());
closesocket(s);
WSACleanup();
return 1;
}
printf("\nMessage: %s\n", message);
return 0;
}