UDP套接字revfrom()返回错误

时间:2016-03-29 19:11:54

标签: c++ udp

目的: 我的代码是创建一个套接字并从客户端接收一个包(该客户端每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;
}

1 个答案:

答案 0 :(得分:1)

您所看到的行为是预期的。您已将套接字设置为非阻塞。因此,如果您致电recvfrom并且此时无法接收,则会返回-1而非阻止。