52

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 utilize these to find the ip address?

Thanks!

Currently trying

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

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

bobber205
  • 12,948
  • 27
  • 74
  • 100

4 Answers4

93

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 + " connected on port number " + localIpEndPoint.Port);
}
Marcos Dimitrio
  • 6,651
  • 5
  • 38
  • 62
Cory Charlton
  • 8,868
  • 4
  • 48
  • 68
8
string ip = ((IPEndPoint)(testsocket.RemoteEndPoint)).Address.ToString();
Filipe Borges
  • 2,712
  • 20
  • 32
buzzard51
  • 1,372
  • 2
  • 23
  • 40
5

RemoteEndPoint is a property, its type is System.Net.EndPoint which inherits from System.Net.IPEndPoint.

If you take a look at IPEndPoint's members, you'll see that there's an Address property.

Bertrand Marron
  • 21,501
  • 8
  • 58
  • 94
-2

I've made this code in VB.NET but you can translate. Well pretend you have the variable Client as a TcpClient

Dim ClientRemoteIP As String = Client.Client.RemoteEndPoint.ToString.Remove(Client.Client.RemoteEndPoint.ToString.IndexOf(":"))

Hope it helps! Cheers.

Marshall
  • 392
  • 1
  • 4
  • 11
  • 1
    You don't have to do all those string functions. It is much faster to just cast to IPEndPoint - DirectCast(Client.Client.RemoteEndPoint, IPEndPoint).Address – JDC Apr 18 '18 at 08:59