Reputation:
I have been trying to figure this out but cannot find a reliable way to get a clients IP address when making a request to a page in asp.net that works with all servers.
Upvotes: 29
Views: 59876
Reputation: 307
You can use HttpContext with property bellow:
var _request1 = HttpContext.Current.Request.UserHostAddress;
string requestedDomain = HttpContext.Current.Request.ServerVariables["HTTP_HOST"];
string requestScheme = HttpContext.Current.Request.Url.Scheme;
string requestQueryString = HttpContext.Current.Request.ServerVariables["QUERY_STRING"];
string requestUrl = HttpContext.Current.Request.ServerVariables["URL"];
Upvotes: 0
Reputation: 814
If there are proxies between client and server. HTTP_X_FORWARDED_FOR header can be used.
var ips = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
var clientIp = "";
if (!string.IsNullOrEmpty(ips))
{
string[] addresses = ips.Split(',');
if (addresses.Length != 0)
{
clientIp = addresses[0];
}
}
else
{
clientIp = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
Upvotes: 0
Reputation: 1
Try this code:
var IpAddress = Request.Headers["Referer"][0];
Upvotes: 0
Reputation: 89082
Request.ServerVariables["REMOTE_ADDR"]
To access an index or property on C#, you should use [ ] instead of ( )
Upvotes: 5
Reputation: 1
Use this code:
public static string GetIpAddress()
{
return HttpContext.Current != null ? HttpContext.Current.Request.UserHostAddress : "";
}
Upvotes: 0
Reputation: 40497
One method is to use Request object:
protected void Page_Load(object sender, EventArgs e)
{
lbl1.Text = Request.UserHostAddress;
}
Upvotes: 38