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无法正常工作。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有