How to get IP Address of the Client User?

Getting your visitor IP address is very common requirement for Web Development and there is more confusion about to get IP in best ways.

It will supports all version of .NET Framework (4.8 4.7.2 4.7.1 4.7 4.6.2 4.6.1 4.6 4.5.2 4.5.1 4.5 4.0 3.5 3.0 2.0 1.1)

The Easiest and best way to do the below code:-

string clientIPAddress = Request.UserHostAddress;

When you are testing at your local machine, you will be getting clientIPAddress = After deploying your page on some server or IP, you will be getting correct client IP addresses.

string cIPAddress = ((clientIPAddress == "::1") || (clientIPAddress == "")) ? "" : clientIPAddress;

Note: - If the server is behind a load balancer, then you may need to use Request.ServerVariables["HTTP_X_FORWARDED_FOR"] . In this case proceed with caution and take only the address that the load balancer has added.

public string GetIPAddress()
    string IPAddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

    if (IPAddress == null)
        IPAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

    return IPAddress;

Sometimes if NAT is enabled on web server there are cases when it always picks local IP Address no matter what method you use.

Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..

My Tech Blog - https://www.code-sample.com/
My Books - Book 1 and Book 2

How to get IP Address of the Client User? How to get IP Address of the Client User? Reviewed by Anil Singh on 5:16 AM Rating: (5)
www.code-sample.com/. Powered by Blogger.