5

Possible Duplicate:
Client IP using C#

I use ASP.net and C# and I would like to know how to get the IP address from a visitor on a page.

I would like to see an example of code that retrieves the IP address and also will be able to show if an IP was behind a proxy.

Thanks for your time.

Community
  • 1
  • 1
GibboK
  • 71,848
  • 143
  • 435
  • 658
  • why guys a down vote for this questions? The question pointed by Mat does not deal with Proxy. A comment would be appreciated. – GibboK Sep 07 '11 at 08:49
  • read the answers to that question. Some do deal with proxies. (As for the downvote, I don't know. Probably for "not enough research".) – Mat Sep 07 '11 at 08:50

2 Answers2

9

You could use the UserHostName property on the Request object:

string ip = Request.UserHostName;

As far as your second question about the proxy is concerned, there is no reliable way to achieve this. You could use heuristics to look for some HTTP request headers that might be sent by the proxy server such as Via or X-Forwarded-For.

string header = Request.Headers["Via"] ?? Request.Headers["X-Forwarded-For"];
if (!string.IsNullOrEmpty(header))
{
    // probably the request was forwarded from a proxy server
    // but you cannot be 100% sure as HTTP request headers can be faked
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Thanks Darin for your insight. – GibboK Sep 07 '11 at 09:06
  • to make `request` work you need to add `System.Web.dll` reference, check how to do that [here](http://www.codeproject.com/Questions/422895/The-name-HttpContext-does-not-exist-in-the-current), hope helps some one. – Shaiju T Jun 30 '15 at 07:55
  • "Via" may contain the proxy name but "X-Forwarded-For" the actual ip. Just make sure you chose the right one. – SeriousM Feb 02 '17 at 13:47
-1

so simple dude,

string IP = Request.ServerVariables["REMOTE_HOST"].ToString();
Andrew Whitaker
  • 124,656
  • 32
  • 289
  • 307
Pradip R.
  • 450
  • 1
  • 14
  • 31