按IP地址获取用户位置

Dam*_*mir 70 c# asp.net

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

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

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

Jon*_*eet 40

您需要一个基于IP地址的反向地理编码API ...就像来自ipdata.co的 API一样.我相信有很多选择.

但是,您可能希望允许用户覆盖它.例如,它们可能位于公司VPN上,这使得IP地址看起来像是在不同的国家/地区.

  • 另一个快速准确的地理位置和威胁数据 API 是 [ipregistry.co](https://ipregistry.co)(免责声明:我运行该服务)。 (3认同)
  • @Jonathan:更新了. (2认同)

Off*_*'er 22

使用http://ipinfo.io,如果您每天发出超过1000个请求,则需要付费.

下面的代码需要Json.NET包.

 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;
        }
Run Code Online (Sandbox Code Playgroud)

我使用的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; }
}
Run Code Online (Sandbox Code Playgroud)


Don*_*nut 12

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
Run Code Online (Sandbox Code Playgroud)

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


BJ *_*tel 12

以下代码为我工作.

因为我正在调用一个免费的API请求(json base)IpStack.

    public static string CityStateCountByIp(string IP)
    {
      //var url = "http://freegeoip.net/json/" + IP;
      //var url = "http://freegeoip.net/json/" + IP;
        string url = "http://api.ipstack.com/" + IP + "?access_key=[KEY]";
        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);
            string City = (string)obj["city"];
            string Country = (string)obj["region_name"];                    
            string CountryCode = (string)obj["country_code"];

           return (CountryCode + " - " + Country +"," + City);
           }

  return "";

}
Run Code Online (Sandbox Code Playgroud)

编辑: 首先,它是http://freegeoip.net/现在它的https://ipstack.com/(也许现在付费服务)


小智 7

我尝试过使用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;
Run Code Online (Sandbox Code Playgroud)

对于localhost,它将提供虚拟数据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;
        }


    }
}
Run Code Online (Sandbox Code Playgroud)

  • 您可以添加几行来解释您的解决方案吗?谢谢. (3认同)

BJ *_*tel 6

使用以下网站的请求

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;
}
Run Code Online (Sandbox Code Playgroud)

以下是请求 url 的 Helper。

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;
}
Run Code Online (Sandbox Code Playgroud)


Pra*_*nay 6

我能够使用客户端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;
Run Code Online (Sandbox Code Playgroud)

你可以通过这篇文章了解更多细节.希望它有所帮助!

  • 此处强烈建议不要仅提供链接答案,因为链接将来可能会失效。我建议您引用您引用的来源来编辑您的答案。 (2认同)

Chu*_*ebs 5

您可能不得不使用外部API,其中大部分都要花钱.

我确实找到了这个,似乎是免费的:http://hostip.info/use.html

  • 提到的网址已不再可用,但现在可以在http://www.hostip.info/use.html找到该API的详细信息 (2认同)

Gre*_*Cat 5

您需要的是“地理IP 数据库”。他们中的大多数都花费了一些钱(尽管不是太贵),尤其是相当精确的。使用最广泛的数据库之一MaxMind 的数据库。他们有一个相当不错的免费版本的 IP 到城市数据库,称为GeoLity City - 它有很多限制,但如果你能应付,那可能是你最好的选择,除非你有一些钱可以订阅更准确的产品。

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