Getting the IP Address of a Remote Socket Endpoint

后端 未结 4 525
温柔的废话
温柔的废话 2020-12-03 00:58

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

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

How do I ut

4条回答
  •  一向
    一向 (楼主)
    2020-12-03 01:34

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

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

提交回复
热议问题