通过IP地址获取用户位置

我有一个用C#编写的ASP.NET网站。

在这个网站上,我需要根据用户的位置自动显示一个开始页面。

我可以根据用户的IP地址获取用户的城市名称吗?

您需要一个基于IP地址的反向地理编码API …就像来自ipdata.co的一个 。 我确定有很多可用的选项。

但是,您可能希望允许用户覆盖此项。 例如,他们可能在公司的VPN上,这使得IP地址看起来像在不同的国家。

IPInfoDB有一个可以调用的API来查找基于IP地址的位置。

对于“City Precision”,你可以这样调用它(你需要注册才能获得一个免费的API密钥):

  http://api.ipinfodb.com/v2/ip_query.php?key=<your_api_key>&ip=74.125.45.100&timezone=false 

这里是VB和C#中的一个例子 ,展示了如何调用API。

我最近find了一个答案,我注意到大多数答案都包含了不完整的链接,所以我决定发布我为帮助新开发人员所做的解决scheme。

  public static string GetUserCountryByIp(string ip) { IpInfo ipInfo = new IpInfo(); try { string info = new WebClient().DownloadString("http://ipinfo.io/" + ip); ipInfo = JsonConvert.DeserializeObject<IpInfo>(info); RegionInfo myRI1 = new RegionInfo(ipInfo.Country); ipInfo.Country = myRI1.EnglishName; } catch (Exception) { ipInfo.Country = null; } return ipInfo.Country; } 

和我使用的IpInfo类:

 public class IpInfo { [JsonProperty("ip")] public string Ip { get; set; } [JsonProperty("hostname")] public string Hostname { get; set; } [JsonProperty("city")] public string City { get; set; } [JsonProperty("region")] public string Region { get; set; } [JsonProperty("country")] public string Country { get; set; } [JsonProperty("loc")] public string Loc { get; set; } [JsonProperty("org")] public string Org { get; set; } [JsonProperty("postal")] public string Postal { get; set; } } 

注意我使用了http://ipinfo.io ,如果你每天提出1000个请求,你需要付钱。

上面的代码需要Json.NET包。

返回国家

 static public string GetCountry() { return new WebClient().DownloadString("http://api.hostip.info/country.php"); } 

用法:

 Console.WriteLine(GetCountry()); // will return short code for your country 

返回信息

 static public string GetInfo() { return new WebClient().DownloadString("http://api.hostip.info/get_json.php"); } 

用法:

 Console.WriteLine(GetInfo()); // Example: // { // "country_name":"COUNTRY NAME", // "country_code":"COUNTRY CODE", // "city":"City", // "ip":"XX.XXX.XX.XXX" // } 

你所需要的就是所谓的“地理IP数据库”。 他们大多花费一些钱(尽pipe不是太贵),特别是相当精确的。 其中最广泛使用的是MaxMind的数据库 。 他们有一个相当不错的免费版本的IP到城市的数据库叫GeoLity City – 它有很多的限制,但是如果你可以应付那可能是你最好的select,除非你有一些钱来订购更精确的产品。

而且,是的,他们确实有一个C#API来查询可用的地理IP数据库 。

我已经尝试使用http://ipinfo.io和这个JSON API完美的作品。 首先,你需要添加下面提到的命名空间:

 using System.Linq; using System.Web; using System.Web.UI.WebControls; using System.Net; using System.IO; using System.Xml; using System.Collections.Specialized; 

对于本地主机,它将虚拟数据作为AU 。 您可以尝试对您的IP进行硬编码并获得结果:

 namespace WebApplication4 { public partial class WebForm1 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string VisitorsIPAddr = string.Empty; //Users IP Address. if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null) { //To get the IP address of the machine and not the proxy VisitorsIPAddr = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString(); } else if (HttpContext.Current.Request.UserHostAddress.Length != 0) { VisitorsIPAddr = HttpContext.Current.Request.UserHostAddress;`enter code here` } string res = "http://ipinfo.io/" + VisitorsIPAddr + "/city"; string ipResponse = IPRequestHelper(res); } public string IPRequestHelper(string url) { string checkURL = url; HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url); HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse(); StreamReader responseStream = new StreamReader(objResponse.GetResponseStream()); string responseRead = responseStream.ReadToEnd(); responseRead = responseRead.Replace("\n", String.Empty); responseStream.Close(); responseStream.Dispose(); return responseRead; } } } 

我能够使用客户端IP地址和freegeoip.net API在ASP.NET MVC中实现这一点。 freegeoip.net是免费的,不需要任何许可证。

以下是我使用的示例代码。

 String UserIP = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; if (string.IsNullOrEmpty(UserIP)) { UserIP = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; } string url = "http://freegeoip.net/json/" + UserIP.ToString(); WebClient client = new WebClient(); string jsonstring = client.DownloadString(url); dynamic dynObj = JsonConvert.DeserializeObject(jsonstring); System.Web.HttpContext.Current.Session["UserCountryCode"] = dynObj.country_code; 

你可以通过这个post了解更多细节。希望它有帮助!

你可能不得不使用一个外部的API,其中大部分花钱。

我确实发现这一点,似乎是免费的: http : //hostip.info/use.html

以下代码为我工作。

正如我所说的免费API请求(json base) siteLink 。

  public static string CityStateCountByIp(string IP) { var url = "http://freegeoip.net/json/" + IP; var request = System.Net.WebRequest.Create(url); using (WebResponse wrs = request.GetResponse()) using (Stream stream = wrs.GetResponseStream()) using (StreamReader reader = new StreamReader(stream)) { string json = reader.ReadToEnd(); var obj = JObject.Parse(json); var City = (string)obj["city"]; // - For Country = (string)obj["region_name"]; //- For CountryCode = (string)obj["country_code"]; return (City); } return ""; } 

使用以下网站的请求

http://ip-api.com/

以下是返回国家和国家代码的C#代码

 public string GetCountryByIP(string ipAddress) { string strReturnVal; string ipResponse = IPRequestHelper("http://ip-api.com/xml/" + ipAddress); //return ipResponse; XmlDocument ipInfoXML = new XmlDocument(); ipInfoXML.LoadXml(ipResponse); XmlNodeList responseXML = ipInfoXML.GetElementsByTagName("query"); NameValueCollection dataXML = new NameValueCollection(); dataXML.Add(responseXML.Item(0).ChildNodes[2].InnerText, responseXML.Item(0).ChildNodes[2].Value); strReturnVal = responseXML.Item(0).ChildNodes[1].InnerText.ToString(); // Contry strReturnVal += "(" + responseXML.Item(0).ChildNodes[2].InnerText.ToString() + ")"; // Contry Code return strReturnVal; } 

以下是助手请求url。

 public string IPRequestHelper(string url) { HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url); HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse(); StreamReader responseStream = new StreamReader(objResponse.GetResponseStream()); string responseRead = responseStream.ReadToEnd(); responseStream.Close(); responseStream.Dispose(); return responseRead; } 

这对你来说是个很好的例子:

 public class IpProperties { public string Status { get; set; } public string Country { get; set; } public string CountryCode { get; set; } public string Region { get; set; } public string RegionName { get; set; } public string City { get; set; } public string Zip { get; set; } public string Lat { get; set; } public string Lon { get; set; } public string TimeZone { get; set; } public string ISP { get; set; } public string ORG { get; set; } public string AS { get; set; } public string Query { get; set; } } public string IPRequestHelper(string url) { HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url); HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse(); StreamReader responseStream = new StreamReader(objResponse.GetResponseStream()); string responseRead = responseStream.ReadToEnd(); responseStream.Close(); responseStream.Dispose(); return responseRead; } public IpProperties GetCountryByIP(string ipAddress) { string ipResponse = IPRequestHelper("http://ip-api.com/xml/" + ipAddress); using (TextReader sr = new StringReader(ipResponse)) { using (System.Data.DataSet dataBase = new System.Data.DataSet()) { IpProperties ipProperties = new IpProperties(); dataBase.ReadXml(sr); ipProperties.Status = dataBase.Tables[0].Rows[0][0].ToString(); ipProperties.Country = dataBase.Tables[0].Rows[0][1].ToString(); ipProperties.CountryCode = dataBase.Tables[0].Rows[0][2].ToString(); ipProperties.Region = dataBase.Tables[0].Rows[0][3].ToString(); ipProperties.RegionName = dataBase.Tables[0].Rows[0][4].ToString(); ipProperties.City = dataBase.Tables[0].Rows[0][5].ToString(); ipProperties.Zip = dataBase.Tables[0].Rows[0][6].ToString(); ipProperties.Lat = dataBase.Tables[0].Rows[0][7].ToString(); ipProperties.Lon = dataBase.Tables[0].Rows[0][8].ToString(); ipProperties.TimeZone = dataBase.Tables[0].Rows[0][9].ToString(); ipProperties.ISP = dataBase.Tables[0].Rows[0][10].ToString(); ipProperties.ORG = dataBase.Tables[0].Rows[0][11].ToString(); ipProperties.AS = dataBase.Tables[0].Rows[0][12].ToString(); ipProperties.Query = dataBase.Tables[0].Rows[0][13].ToString(); return ipProperties; } } } 

并testing:

 var ipResponse = GetCountryByIP("your ip address or domain name :)"); 

使用API​​的替代方法是使用HTML 5位置导航器来查询关于用户位置的浏览器。 我正在寻找一个类似的方法,在主题的问题,但我发现,HTML 5导航工程更好,更便宜的我的情况。 请考虑你的scinario可能会有所不同。 使用Html5获取用户位置非常简单:

 function getLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition); } else { console.log("Geolocation is not supported by this browser."); } } function showPosition(position) { console.log("Latitude: " + position.coords.latitude + "<br>Longitude: " + position.coords.longitude); } 

http://www.w3schools.com/html/html5_geolocation.asp上自己试试;