我正在尝试根据网络API中的IP地址获取用户所在的国家/地区。使用userhostaddress,它返回一个私有IP,而不是它们的公共IP。
这就是我一直在尝试的:
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();