Vicky Vicky - 5 days ago 6
C# Question

HttpListenerContext.Request.RemoteEndPoint Ipaddress behaviour

I have a piece of code in a service which listens to a port and then logs the IP addresses using the HttpListenerContext.Request.RemoteEndPoint

I have noticed, that in one machine "A" when the remote endpoint is also on the same machine A, HttpListenerContext.Request.RemoteEndPoint returns the IP address of the machine A i.e something like 192.168.20.12

Where as when the same piece of code is run on a different machine B, with the remote endpoint also in the same machine B, the HttpListenerContext.Request.RemoteEndPoint returns 127.0.0.1

Does anybody know why there is a difference ?

For my application, I would like to have the proper IP address(192.168.20.12) and not the loopback address. How can one go about getting this information ?

More info : Machine A is a physical desktop running windows 7. Machine B is an EC2 instance running windows server 2012.

DVK DVK
Answer

The problem isn't that HttpListenerContext.Request.RemoteEndPoint is returning the wrong IP address... the issue is that whatever is connecting to the port is connecting to the loopback address and your listener is correctly reporting that. Assuming that you actually want to use your listener to monitor connections from a remote machine, this is really an immaterial concern (since you can't connect to the loopback address from a remote machine). Likewise, if a machine connecting to your port has multiple IP addresses, you aren't going to be able to choose which one HttpListenerContext.Request.RemoteEndPoint returns. It should return whichever IP address the remote machine selected to connect to your server.

Comments