Reputation: 6530
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?
Upvotes: 3
Views: 8516
Reputation: 38130
If you connect via the localhost address, then your client address will also report as localhost (as it will route through the loopback adapter)
Upvotes: 1
Reputation: 10008
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"];
}
Upvotes: 5