gpt4 book ai didi

c++ - UDP 套接字 revfrom() 返回错误

转载 作者:行者123 更新时间:2023-11-28 05:45:37 26 4
gpt4 key购买 nike

目的:我的代码是创建一个套接字并从客户端接收一个包(这个客户端每 500 毫秒广播一次消息)。现象:当套接字被创建为主机套接字时,直接使用 revfrom() 将从 revfrom 函数返回 -1。但是,如果我对任何数据包使用 sendto() 函数,则立即使用 revfrom()。这将有助于找到我需要的数据包。用谷歌搜索,它看起来像一个客户端套接字,但我将它创建为服务器套接字。下面是我的代码,有什么建议请指教,不胜感激!代码:

SOCKET s;
sockaddr_in addrDest;
sockaddr_in addrLocal;
int result;
char udp_buff[AMP_MAX_PACKET_SIZE];

WSADATA wsaData;
wchar_t msgbuf[100];

int addrDestSize = sizeof(SOCKADDR_IN);

// initialize winsock
result = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (result != NO_ERROR) {
wprintf(L"WSAStartup failed with error: %d\n", result);
//return 1;
}

// create the socket
s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); // UDP socket

u_long iMode = 1;
result = ioctlsocket(s, FIONBIO, &iMode);
if (result != NO_ERROR)
printf("ioctlsocket failed with error: %ld\n", result);

addrLocal.sin_family = AF_INET;
addrLocal.sin_port = htons(16717);
addrLocal.sin_addr.s_addr = htonl(INADDR_ANY); // zero-init sin_addr to tell it to use all available adapters on the local host

// associate this socket with local UDP port 16717
result = bind(s, (struct sockaddr*)&addrLocal, sizeof(addrLocal));

addrDest.sin_family = AF_INET;
addrDest.sin_port = htons(16717);
inet_pton(AF_INET, "192.168.99.255", &(addrDest.sin_addr));

uint8_t node_address_temp[6] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; //array
std::vector<uint8_t> node_address(node_address_temp, node_address_temp + sizeof(node_address_temp) / sizeof(uint8_t));
//formatDataPack("MID", dataPack, node_address);
//SendCMDToGauge(&s, &dataPack, &addrDest);
result = sendto(s, " ", strlen(" ") + 1, 0, (SOCKADDR *)&addrDest, sizeof(addrDest));

result = -1;
while (result < 0 ) {
result = recvfrom(s, (char*)&udp_buff, sizeof(udp_buff), 0, (SOCKADDR *)&addrDest, &addrDestSize);
//result = recv(s, (char*)&udp_buff, sizeof(udp_buff), 0);
swprintf(msgbuf, 100, L"Revfrom Result: %d\n", result);
OutputDebugString(msgbuf);
Sleep(500);
if (result = 36)
result = -1;
}

最佳答案

您看到的行为是预期的。您已将套接字设置为非阻塞。因此,如果您调用 recvfrom 并且此时没有任何可接收的内容,它将返回 -1 而不是阻塞。

关于c++ - UDP 套接字 revfrom() 返回错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36293130/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com