其实这个错误码纯属微软误导我们,这个socket是连接上的。寻找原因,发现如下一段话,不在getpeername的文档里,而在AcceptEx的文档里,晕菜。
When the AcceptEx function returns, the socket sAcceptSocket is in the default state for a connected socket. The socket sAcceptSocket does not inherit the properties of the socket associated with sListenSocket parameter until SO_UPDATE_ACCEPT_CONTEXT is set on the socket. Use the setsockopt function to set the SO_UPDATE_ACCEPT_CONTEXT option, specifying sAcceptSocket as the socket handle and sListenSocket as the option value.
For example:
err = setsockopt( sAcceptSocket,
SOL_SOCKET,
SO_UPDATE_ACCEPT_CONTEXT,
(char *)&sListenSocket,
sizeof(sListenSocket) );
但是微软并没有确切的说明这一段代码应该在何时执行,注意在setsockopt的文档中有这样一段话:
SO_UPDATE_ACCEPT_CONTEXT | int | Updates the accepting socket with the context of the listening socket. |
“使用listening socket的上下文更新accepting socket”,可见,只有当连接连入成功后,listening socket才会出现正确的上下文,所以,需要在
完成端口返回成功或GetOverlappedResult 返回成功之后执行。将可以正确得到远端信息。