IOCP中使用getpeername出错,返回10014的解决方法。

来源:互联网 发布:matlab 矩阵列归一化 编辑:程序博客网 时间:2024/06/09 18:55

IOCP中使用getpeername出错, WSAGetLastError 的返回值是10014。


与朋友讨论后,经指点。得到此解决方法。记录并致谢。

此问题不是在所有电脑上都会出现。我自己的Win7 x86会出现此错误。到我朋友的Win7 x86中却运行正常。在Windows Server2008 R2 x64 中测试也正常。


原代码:

sockaddr_in sockAddr;memset(&sockAddr, 0, sizeof(sockAddr));socklen_t nSockAddrLen = sizeof(sockAddr);if ( SOCKET_ERROR == getpeername( m_hSocket, (sockaddr*)&sockAddr, &nSockAddrLen ) ) {return false;}m_nWanPort = ntohs(sockAddr.sin_port);m_strWanIP = inet_ntoa(sockAddr.sin_addr);


经查MSDN

http://msdn.microsoft.com/en-us/library/ms737524(VS.85).aspx


里面提及

The buffer size for the local and remote address must be 16 bytes more than the size of the sockaddr structure for the transport protocol in use because the addresses are written in an internal format. For example, the size of a sockaddr_in (the address structure for TCP/IP) is 16 bytes. Therefore, a buffer size of at least 32 bytes must be specified for the local and remote addresses.


代码修改为如下:

sockaddr_in sockAddr[2];memset(&sockAddr, 0, sizeof(sockAddr));socklen_t nSockAddrLen = sizeof(sockAddr);if ( SOCKET_ERROR == getpeername( m_hSocket, (sockaddr*)&sockAddr, &nSockAddrLen ) ) {return false;}m_nWanPort = ntohs(sockAddr[0].sin_port);m_strWanIP = inet_ntoa(sockAddr[0].sin_addr);


修改后,经测试正常。但想不明白为什么我朋友的系统中运行起原来的代码也是正常的。如有了解的同仁请告知。


0 0
原创粉丝点击