0

Below is my code, when I run in local, it can successfully return my public IP address. But when I host the website to the server, it always returns server public IP address. Does anyone know what is the root cause? I wish to get the public IP address from my client who is using the page I created.

static string GetPublicIPAddress()
{
    string address = "";
    try
    {
        WebRequest request = WebRequest.Create("https://bot.whatismyipaddress.com");
        using (WebResponse response = request.GetResponse())
        using (StreamReader stream = new StreamReader(response.GetResponseStream()))
        {
            address = stream.ReadToEnd();
        }
        
       
    }
    catch(Exception ex) {
        address = ex.Message;
    }
    return address;
}

The server is hosting internally.

I even try using different web addresses as below:

https://api.ipify.org

https://ipinfo.io/ip

https://wtfismyip.com/text

https://checkip.amazonaws.com/

https://bot.whatismyipaddress.com

https://ipecho.net/plain

Ng Zheng
  • 59
  • 1
  • 12
  • Yeah, this is never going to work. Try looking at the actual request – TheGeneral Aug 27 '21 at 02:46
  • Your code is asking another server what the caller's IP is, which as the server means you're the caller. Depending on what version of asp.net you're on this answer will likely work to get the caller's IP: https://stackoverflow.com/a/64765977/1561465 – siva.k Aug 27 '21 at 02:52
  • @TheGeneral thanks for your answer. Can you please explain more about what you mean actual request? – Ng Zheng Aug 27 '21 at 03:15
  • @siva.k Thanks for your explanation. I try using the method your provided, but all my client IP addresses return the same IP like 192.168.x.x – Ng Zheng Aug 27 '21 at 03:16
  • Does this answer your question? [HOWTO: Get client IP address from request in ASP.NET MVC](https://stackoverflow.com/questions/64722540/howto-get-client-ip-address-from-request-in-asp-net-mvc) – JuanR Aug 27 '21 at 06:09
  • @NgZheng that is expected when running locally because your IP will be your local machines local network IP. When deployed outside of your local network you will then get real public IPs. – siva.k Aug 28 '21 at 04:09

0 Answers0