C#

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 = 127.0.0.1. After deploying your page on some server or IP, you will be getting correct client IP addresses.

string cIPAddress = ((clientIPAddress == "::1") || (clientIPAddress == "127.0.0.1")) ? "149.202.91.218" : 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

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 Blogs - https://code-sample.com and https://code-sample.xyz
My Book1 - BEST SELLING ANGULAR BOOK (INCLUDING ALL VERSIONS 2, 4, 5, 6, 7)
My Book2 - ANGULAR 2 INTERVIEW QUESTIONS BOOK - Both Books are Available on WorldWide.

www.code-sample.com/. Powered by Blogger.
^