C# get ip address of client machine(3 methods)

Lionsure 2020-08-11 Original by the website

There are usually three methods to get the client IP address in C#, the first one uses HTTP_X_FORWARDED_FOR, the second uses REMOTE_ADDR, the third uses UserHostAddress; all three methods use Request.

Sometimes, it may not be possible to get the IP in a certain way, so it is best to use the three methods at the same time, of course, you need to add if judgment. Next, introduce each method first, and then encapsulate the three methods into a callable method.

 

1. C# get ip with HTTP_X_FORWARDED_FOR

///<summary>
       /// C# get ip address of client machine<
       ///</summary>
       ///<returns>IP address</returns>

       public string GetClientIPAddr()
       {
              return Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
       }

 

2. C# get ip with REMOTE_ADDR

///<summary>
       ///C# get ip address of client machine
       ///</summary>
       ///<returns>IP address</returns>

       public string GetClientIPAddr()
       {
              return Request.ServerVariables["REMOTE_ADDR"];
       }

 

3. C# get ip with UserHostAddress

///<summary>
       ///C# get ip address of client machine
       ///</summary>
       ///<returns>IP address</returns>

       public string GetClientIPAddr()
       {
              return Request.UserHostAddress;
       }

 

4. Three methods are used together to get IP(can be directly called)

///<summary>
       ///C# get ip address of client machine
       ///</summary>
       ///<returns>IP address</returns>

       public string GetClientIPAddr()
       {
              string ipAddr = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
              if (string.IsNullOrEmpty(ipAddr))
                     ipAddr = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

       if (string.IsNullOrEmpty(ipAddr))
                     ipAddr = HttpContext.Current.Request.UserHostAddress;

       return ipAddr;
       }

The above method of obtaining an IP address has passed the test in practical applications, they can accurately get the client IP address; if you want to use it, just use the fourth combination method.