Getting requesting client's IP address on server

9.8k views Asked by At

I have a HttpListener where I'm interested in being able to see the IP address of the requesting clients. A bonus would also being able to see the DNS of the client, but I'm not sure how that would be possible since as far as I know that information is not being sent with HTTP?

Anyway, as far as I can see, I should be able to use Request.UserHostAddress for this, but I'm just getting my local IP address. What am I doing wrong here?

Where I should get the client IP.

        HttpListenerContext context = listener.EndGetContext(result);
        string clientName = context.Request.UserHostAddress;

Where I'm writing out on a server output listbox I have:

        public static void TileString(int x, int y, int z, string dbName, string clientName)
        {
        int[] tileInts = { z, x, y };
        string tileString = string.Join("/", tileInts);

        Application.Current.Dispatcher.Invoke(new Action(() =>
        {
            var mainWindow = Application.Current.MainWindow as MainWindow;
            mainWindow.AppendServerOutput("Delivering tile " + tileString + " in format [z, x, y]" + " from " + dbName + " to client " + clientName + "\n");
        }));
        }
2

There are 2 answers

2
Sjips On BEST ANSWER

try to use:

string clientIP = context.Request.RemoteEndPoint.ToString());
2
Peter Duniho On

From the MSDN documentation for the HttpListenerRequest.UserHostAddress property:

Gets the server IP address and port number to which the request is directed.

In other words, it's not the remote end-point's address. It's the address of the server that the remote end-point used.

As you have seen, you can use the RemoteEndPoint to retrieve the IP address of the remote end-point.

Use the System.Net.Dns.GetHostEntry() method to do reverse-DNS lookups (i.e. retrieve the remote host name for the IP address).