WSASendTo定期失败10014

时间:2017-12-21 17:26:45

标签: c windows winsock winsock2

我创建了一个UDP套接字,并尝试使用WSASendTo在其上发送一些数据。这有时 ,但偶尔会失败(使用WSAEFAULT),我似乎无法追踪它。

首先,我设置Winsock2并创建我的UDP套接字:

const char* host = "127.0.0.1";
int port = 10000;

WSADATA wsd = { 0 };

if (WSAStartup(MAKEWORD(2, 2), &wsd) != 0) {
    return 1;
}

int socktype = SOCK_DGRAM;
int family = AF_INET;
int protocol = IPPROTO_UDP;

SOCKET sock = WSASocketW(family,
        socktype,
        protocol,
        NULL,
        0,
        WSA_FLAG_OVERLAPPED);

然后我使用我的IP和端口获得addr结构设置:

struct sockaddr_in addr;
int addr_size = sizeof(addr);

addr.sin_family = AF_INET;
inet_pton(AF_INET, host, (void*)addr.sin_addr);
addr.sin_port = htons((u_short)port);

最后,我使用WSASendTo发送数据:

// `overlapped` and `buf` are both declared at a higher scope so
// that they are available in the completion routine.
WSAOVERLAPPED overlapped = { 0 }
WSABUF buf;


buf.buf = data;
buf.len = size;

char* data = "Hello, World!";
int size = strlen(data);

// Returns -1 here, with WSAGetLastError() == 10014.
ret = WSASendTo(sock,
        &buf,
        1,
        &bytes_sent,
        flags,
        (SOCKADDR*)&addr,
        &addr_size,
        &overlapped,
        SendCompletion);

此时ret等于-1并且对WSAGetLastError的调用会返回997(WSA_IO_PENDING,我期望)或大约一半的时间10014 1}}(WSAEFAULT)。

根据文档,这意味着:

  

lpBuffers,lpTo,lpOverlapped,lpNumberOfBytesSent或lpCompletionRoutine参数不是用户地址空间的一部分,或者lpTo参数太小。

我已经完成并验证了这些出现的内容是正确的。也就是说,地址似乎是合理的,lpTo之类的东西的大小是正确的。

知道为什么这有时会失败?

0 个答案:

没有答案