views:

154

answers:

2

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

I have tried all of the below things , but I am getting the same output: 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?

+1  A: 

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

REMOTE_ADDR is the header that contains the clients ip address you should check that first.

You should also check to for the HTTP_X_FORWARDED header in case you're visitor is going through a proxy. Be aware that HTTP_X_FORWARDED is an array that can contain multiple comma separated values depending on the number of proxies.

Here is a small c# snippet that shows determining the client's 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"];
 }
vfilby
Also be aware that System.Net.Dns.GetHostName will get the address of the local machine that you are running on!
vfilby
Does that mean that after deploying to the server this code wil work fine ? string ipaddress = string.Empty ; ipaddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; if (ipaddress == "" || ipaddress == null) ipaddress = Request.ServerVariables["REMOTE_ADDR"];
Zerotoinfinite
Not necessarily, HTTP_X_FORWARDED_FOR can be a single ip address or an array of ip address, you may need to take that into account. Otherwise I think it should work, you can always try exposing the code on your local machine via IIS, then connecting through a different computer to see what ip it reports. You might also want to consider `String.IsNullOrEmpty( ... ) ` instead of `(ipaddr = "" || ipaddr == null`.
vfilby
A: 

If you connect via the localhost address, then your client address will also report as localhost (as it will route through the loopback adapter)

Rowland Shaw