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

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);


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


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值