3

How can i get IP address of client machine in C#.? I want to keep a log register for my online application and to keep IP address of logging system i want to get the IP address of client....

Advance Thanks...

Nithesh Narayanan
  • 11,481
  • 34
  • 98
  • 138

2 Answers2

8
    String clientIP = 
(HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]==null)?
HttpContext.Current.Request.UserHostAddress:
HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
Chandu
  • 81,493
  • 19
  • 133
  • 134
  • 1
    As Wikipedia [notes](http://en.wikipedia.org/wiki/X-Forwarded-For), the value of this header may be bogus. Thus, it's safer to keep a whitelist of IPs for which you trust it. – Matthew Flaschen Dec 29 '10 at 05:32
  • 3
    String clientIP = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]?? HttpContext.Current.Request.UserHostAddress is this not more readable? +1 one for proxy checking – naveen Dec 29 '10 at 05:38
  • Indeed it is more readable, but I was not sure of .Net version OP is using. – Chandu Dec 29 '10 at 05:41
6
HttpContext.Current.Request.UserHostAddress

This doesn't attempt to take into account proxies. For that, you can use Request.ServerVariables["HTTP_X_FORWARDED_FOR"]. However, make sure you're not trusting that blindly, since it could be forged. It's better to keep a whitelist of IPs for which you trust it.

Matthew Flaschen
  • 278,309
  • 50
  • 514
  • 539