0
我是Windows套接字編程的新手。我有一個設備通過基於ipv6協議的端口提供udp數據。我試圖在Windows 7的Visual Studio中編寫的控制檯應用程序中捕獲此信息。套接字創建和綁定成功,但沒有收到指定的端口。在Windows套接字程序中未收到udp數據
我已經在Linux中完成了這個工作,因爲我基本上是一個Linux系統軟件開發人員,它工作的很完美。還有什麼我需要做的,以獲得窗口中的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;
}
Ho關於你的防火牆設置?你檢查過那些嗎? –
我已通過禁用Windows防火牆測試,但仍然無奈.. – Rouf