我是 Windows 套接字编程的新手。我有一个设备,它通过基于 ipv6 协议的端口提供 udp 数据。我试图在 Windows 7 中用 Visual Studio 编写的控制台应用程序中捕获这一点。套接字创建和绑定成功,但没有从指定的端口收到任何内容。
我已经在 Linux 中完成了这项工作,因为我基本上是一名 linux 系统软件开发人员,并且它运行良好。我还需要做什么才能在 Windows 中获取 UDP 数据包。我在 windows 中检查了 wireshark,发现 UDP 数据包是从设备到 PC 的。
在 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);
}
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;
}