欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-03-27 08:33:40
ip-api.com接口(解析 json需要引入newtonsoft.json.dll ):/// /// 根据ip 获取物理地址 ///

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;
    }

到此这篇关于c#根据ip地址查询所属地区实例详解的文章就介绍到这了,更多相关c#根据ip地址查询所属地区内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

相关标签: C# 查询地区