欢迎来到代码驿站!

.NET代码

当前位置:首页 > 软件编程 > .NET代码

C#根据IP地址查询所属地区实例详解

时间:2021-11-26 11:55:36|栏目:.NET代码|点击:

ip-api.com接口(解析 json需要引入Newtonsoft.Json.dll ):

/// <summary> 
    /// 根据IP 获取物理地址 
    /// </summary> 
    /// <param name="ip">Ip地址</param> 
    /// <returns></returns> 
    public static string GetIpAddress(string ip)
    {
      string url = "http://ip-api.com/json/"+ip+"?lang=zh-CN";
      string result = "";
      WebRequest wrt = null;
      WebResponse wrp = null;
      try
      {
        wrt = WebRequest.Create(url);
        wrt.Credentials = CredentialCache.DefaultCredentials;
 
        wrp = wrt.GetResponse();
        StreamReader sr = new StreamReader(wrp.GetResponseStream(), Encoding.UTF8);
        //获取到的是Json数据
        string html = sr.ReadToEnd();
 
        //Newtonsoft.Json读取数据
        JObject obj = JsonConvert.DeserializeObject<JObject>(html);
        string city = obj["city"].ToString();
        string province = obj["regionName"].ToString();
        result = city.Equals(province) ? city : (province + city);
      }
      catch (Exception)
      {
      }
      finally
      {
        if (wrp != null)
          wrp.Close();
        if (wrt != null)
          wrt.Abort();
      }
      return result;
    }

126.net接口: 

/// <summary> 
    /// 根据IP 获取物理地址 
    /// </summary> 
    /// <param name="ip">Ip地址</param> 
    /// <returns></returns> 
    public static string GetstringIpAddress(string ip)
    {
      string url = "http://ip.ws.126.net/ipquery?ip="+ip;
      string result="";
      WebRequest wrt = null;
      WebResponse wrp = null;
      try
      {
        wrt = WebRequest.Create(url);
        wrt.Credentials = CredentialCache.DefaultCredentials;
 
        wrp = wrt.GetResponse();
        StreamReader sr = new StreamReader(wrp.GetResponseStream(), Encoding.Default);
        //获取到的数据格式:var lo="江苏省", lc="镇江市"; var localAddress={city:"镇江市", province:"江苏省"}
        string html = sr.ReadToEnd();
        string pattern = "{city:\"(?<key1>.*?)\", province:\"(?<key2>.*?)\"}";
        Regex regex = new Regex(pattern, RegexOptions.None);
        Match match = regex.Match(html);
        string city=match.Groups["key1"].Value;
        string province=match.Groups["key2"].Value;
        result = city.Equals(province) ? city : (province + city);
      }
      catch (Exception)
      {
      }
      finally
      {
        if (wrp != null)
          wrp.Close();
        if (wrt != null)
          wrt.Abort();
      }
      return result;
    }

上一篇:.NET发送邮件的实现方法示例

栏    目:.NET代码

下一篇:SignalR Self Host+MVC等多端消息推送服务(一)

本文标题:C#根据IP地址查询所属地区实例详解

本文地址:http://www.codeinn.net/misctech/184833.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有