Carson
Carson

Reputation:

How do you get the IP address from a request in ASP.NET?

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

Answers (8)

Apple Yellow
Apple Yellow

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

Chinthaka Fernando
Chinthaka Fernando

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

miguel gutierrez
miguel gutierrez

Reputation: 1

Try this code:

var IpAddress = Request.Headers["Referer"][0];

Upvotes: 0

Jason
Jason

Reputation: 89082

Request.ServerVariables["REMOTE_ADDR"]

To access an index or property on C#, you should use [ ] instead of ( )

Upvotes: 5

Elnaz
Elnaz

Reputation: 2890

System.Web.HttpContext.Current.Request.UserHostAddress;

Upvotes: 0

Ankur vijay
Ankur vijay

Reputation: 1

Use this code:

public static string GetIpAddress()
    {
        return HttpContext.Current != null ? HttpContext.Current.Request.UserHostAddress : "";
    }

Upvotes: 0

Taran
Taran

Reputation: 3221

 IpAddress=HttpContext.Current.Request.UserHostAddress;

Upvotes: 8

TheVillageIdiot
TheVillageIdiot

Reputation: 40497

One method is to use Request object:

protected void Page_Load(object sender, EventArgs e)
{
    lbl1.Text = Request.UserHostAddress;
}

Upvotes: 38

Related Questions