如何从套接字中获取的IPEndPoint获取IP地址

时间:2010-06-29 08:12:06

标签: c# sockets tcp network-programming

 ipEndReceive = new IPEndPoint(IPAddress.Parse("127.0.0.1"), receivePort);
 receiveSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream
                          , ProtocolType.Tcp);

 ErrorLog.WritetoErrorlog("Trying to Bind IP Address Stored in  Variable : "
                          +ipEndReceive.Address.ToString()
                          +"\n Port No :"+ipEndReceive.Port.ToString(), logPath);

 receiveSock.Bind(ipEndReceive);


 ErrorLog.WritetoErrorlog("\nRemote IP Address : " 
                    + ((IPEndPoint)receiveSock.RemoteEndPoint).Address.ToString()
                    + "\n Local IP:" 
                    + ((IPEndPoint)receiveSock.LocalEndPoint).Address.ToString()
                    , logPath);

此处receiveSock.RemoteEndPoint返回EndPoint而不是IPEndPoint的实例,因为我无法从收到请求的地方获取远程IP地址。 我们有没有办法从这个插座中获取它。

1 个答案:

答案 0 :(得分:0)

套接字RemoteEndpoint将在连接套接字后设置。

这意味着在绑定后记录RemoteEndpoint是不正确的。

  

在调用Accept或Connect后设置RemoteEndPoint。如果您之前尝试访问此属性,则RemoteEndPoint将抛出SocketException。如果收到SocketException,请使用SocketException :: ErrorCode属性获取特定的错误代码。获取此代码后,请参阅MSDN库中的Windows套接字版本2 API错误代码文档,以获取错误的详细说明。“

(来自MSDN)