0

I'm trying to get a user's country based on IP address in web api. Using userhostaddress it returns a Private IP not their public IP.

This is what I've been trying:

string clientAddress = HttpContext.Current.Request.UserHostAddress;
string nowip = null;
nowip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(nowip)){
    nowip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
}

WebRequest request = WebRequest.Create("http://checkip.dyndns.org");
WebResponse response = request.GetResponse();
StreamReader stream = new StreamReader(response.GetResponseStream());
string ipAddress = stream.ReadToEnd();
indivisible
  • 4,892
  • 4
  • 31
  • 50
  • May we see what you've been trying? – indivisible Apr 30 '14 at 07:07
  • string clientAddress = HttpContext.Current.Request.UserHostAddress; – user3544049 Apr 30 '14 at 07:08
  • nowip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; if (string.IsNullOrEmpty(nowip)) { nowip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString(); } WebRequest request = WebRequest.Create("http://checkip.dyndns.org"); WebResponse response = request.GetResponse(); StreamReader stream = new StreamReader(response.GetResponseStream()); – user3544049 Apr 30 '14 at 07:09
  • You should edit that into your question. – indivisible Apr 30 '14 at 07:10
  • There are a number of questions that can likely help you get your clients' IPs: http://stackoverflow.com/questions/19285957/how-to-get-public-ip-address-of-a-user-in-c-sharp , http://stackoverflow.com/questions/15948201/asp-net-get-external-ip-address , http://stackoverflow.com/questions/2620932/get-users-ip-address . – indivisible Apr 30 '14 at 07:26
  • but i already tried not worked – user3544049 Apr 30 '14 at 07:32
  • There are multiple solutions in those answers, you only showed two attempts above. For instance did you try: `HttpContext.Current.Request.UserHostAddress`? – indivisible Apr 30 '14 at 07:38
  • used already see the first line it returns only private ip not publc – user3544049 Apr 30 '14 at 07:55
  • any answers waiting for help – user3544049 Apr 30 '14 at 10:19

0 Answers0