Windows UDP socket错误码10054,一定要记得处理

发布时间:2025-12-09 11:55:17 浏览次数:10

系统学习Windows客户端开发

A使用UDP socket,调用sendto()函数向B发送数据,但是B没有接收数据发送端口不可达的ICMP报文,之后A调用recvfrom()试图接收目标地址B的数据,recvfrom会返回-1,WSAGetLastError()返回WSAECONNRESET (10054) 连接被对方重置。

奇怪,UDP是无连接,怎么会被对方重置连接呢?

微软官网这么说:If sending a datagram using the sendto function results in an "ICMP port unreachable" response and the select function is set for readfds, the program returns 1 and the subsequent call to the recvfrom function does not work with a WSAECONNRESET (10054) error response. In Microsoft Windows NT 4.0, this situation causes the select function to block or time out.

也就是说,Windows UDP socket将ICMP端口不可达报文的错误,转成WSAECONNRESET 错误码,在recvfrom()时返回。经测试,每次recvfrom()都会这样,所以重试没用只能重新创建socket。

这个问题解决方法是设置socket的工作模式,让底层socket忽略这个错误无需上报。

BOOL bEnalbeConnRestError = FALSE;DWORD dwBytesReturned = 0;WSAIoctl(iSock, SIO_UDP_CONNRESET, &bEnalbeConnRestError, sizeof(bEnalbeConnRestError),          NULL, 0, &dwBytesReturned, NULL, NULL);

使用UDP时,切记要加上这段代码,要不然在某些异常场景就会出现UDP socket无法正常工作。

socket 10054
需要做网站?需要网络推广?欢迎咨询客户经理 13272073477