views:

741

answers:

2

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?

+3  A: 

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);
}
Cory Charlton
It looks like you are converting the address to a string and parsing it back to an IPAddress. Why?
Foole
I'm taking code right from the MSDN page. I know it's ugly code huh?
Cory Charlton
But ya now that I actually look at it I wonder what the author was smoking and where I can get some. Let me clean it up so it doesn't reflect upon me :P
Cory Charlton
That was on MSDN? I thought I was a bad coder.
ChaosPandion
+2  A: 

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
All I see available for RemoteEndPoint's members is AddressFamily. How do I gain access to Address?
bobber205
((System.Net.IPEndPoint)socket.RemoteEndPoint).Address
Bertrand Marron
Thank you! :)I am trying string remoteIP = IPAddress.Parse( testSocket.Address.Address.ToString() ).ToString();and getting "1.0.0.127" instead of "127.0.0.1" for localhost connections. Is this normal?
bobber205