获取远程套接字端点的 IP 地址

问题描述:

如何确定已连接套接字的远程 IP 地址?

How do I determine the remote IP Address of a connected socket?

我有一个可以访问的 RemoteEndPoint 对象及其 AddressFamily 成员.

I have a RemoteEndPoint object I can access and well as its AddressFamily member.

我如何利用这些来查找 IP 地址?

How do I utilize these to find the ip address?

谢谢!

正在尝试

IPAddress.Parse( testSocket.Address.Address.ToString() ).ToString();

并为本地主机端点获取 1.0.0.127 而不是 127.0.0.1.这正常吗?

and getting 1.0.0.127 instead of 127.0.0.1 for localhost end points. Is this normal?

http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.remoteendpoint.aspx

然后您可以调用 IPEndPoint..::.Address 方法检索远程 IPAddress,调用 IPEndPoint..::.Port 方法检索远程端口号.

You can then call the IPEndPoint..::.Address method to retrieve the remote IPAddress, and the IPEndPoint..::.Port method to retrieve the remote port number.

更多来自链接(修复了很多呵呵):

More from the link (fixed up alot heh):

Socket s;

IPEndPoint remoteIpEndPoint = s.RemoteEndPoint as IPEndPoint;
IPEndPoint localIpEndPoint = s.LocalEndPoint as IPEndPoint;

if (remoteIpEndPoint != null)
{
    // Using the RemoteEndPoint property.
    Console.WriteLine("I am connected to " + remoteIpEndPoint.Address + "on port number " + remoteIpEndPoint.Port);
}

if (localIpEndPoint != null)
{
    // Using the LocalEndPoint property.
    Console.WriteLine("My local IpAddress is :" + localIpEndPoint.Address + "I am connected on port number " + localIpEndPoint.Port);
}