Windows UDP socket recvfrom返回10054錯誤的解決辦法

來源:互聯網
上載者:User

標籤:style   blog   http   io   color   os   ar   使用   sp   

現象:

在Windows 7系統上,A使用UDP socket,調用sendto函數向一個目標地址B發送資料,但是目標地址B沒有接收資料,如果A此時立即調用recvfrom試圖接收目標地址B發回的資料的話,recvfrom會立即返回-1,WSAGetLastError()返回10045。

原因:

上述現象是Windows socket的一個bug,當UDP Socket在某次發送後收到一個不可到達的ICMP包時,這個錯誤將在下一個接收中返回,所以上面的通訊端在下一次的接收中返回了SOCKET_ERROR,錯誤是10054。

解決辦法:

使用WSAIoctl設定UDP socket的工作模式,讓其忽略這個錯誤。具體做法如下:

#include <Winsock2.h>#include <Mstcpip.h>#include <stdio.h>#pragma comment(lib, "ws2_32.lib")#define SIO_UDP_CONNRESET _WSAIOW(IOC_VENDOR, 12)BOOL bNewBehavior = FALSE;DWORD dwBytesReturned = 0;WSAIoctl(iSock, SIO_UDP_CONNRESET, &bNewBehavior, sizeof bNewBehavior, NULL, 0, &dwBytesReturned, NULL, NULL);

SIO_UDP_CONNREST選項:Controls whether UDP PORT_UNREACHABLE messages are reported. Set to TRUE to enable reporting. Set to FALSE to disable reporting.

備忘:

  1. setsockopt是修改套介面的屬性,只是該套介面在工作的過程中需要用到的一些參數;WSAIoctl則是修改套介面的工作模式,更多的定義了這個套介面要以怎樣的形式進行工作,有本質的區別。

參考文獻:

[1]. http://blog.csdn.net/wpullo/article/details/5905616
[2]. http://msdn.microsoft.com/zh-cn/ms741621
[3]. http://blog.sina.com.cn/s/blog_536e955201009xqp.html
[4]. http://blog.csdn.net/threewall/article/details/5089817

Windows UDP socket recvfrom返回10054錯誤的解決辦法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.