Client machine IP

Please let me know how to get the client IP address,

I tried all the things listed below, but I get the same result: 127.0.0.1

string strClientIP;
strClientIP = Request.UserHostAddress.ToString();

string strHostName = System.Net.Dns.GetHostName();
string clientIPAddress = System.Net.Dns.GetHostAddresses(strHostName).GetValue(0).ToString();

string ipaddress = string.Empty ;
ipaddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (ipaddress == "" || ipaddress == null)
    ipaddress = Request.ServerVariables["REMOTE_ADDR"];

How can I get the correct IP?

+3
source share
2 answers

You are on the right track with REMOTE_ADDR, but it may not work, if you visit the site locally, it will show the local host.

REMOTE_ADDR is a header containing the IP address of the client that you should check first.

HTTP_X_FORWARDED, . , HTTP_X_FORWARDED - , , , .

#, ip:

 string clientIp = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
 if( !string.IsNullOrEmpty(clientIp) ) {
  string[] forwardedIps = clientIp.Split( new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries );
  clientIp = forwardedIps[forwardedIps.Length - 1];
 } else {
  clientIp = context.Request.ServerVariables["REMOTE_ADDR"];
 }
+4

localhost, localhost ( loopback-)

+1

Source: https://habr.com/ru/post/1741819/


All Articles