C#根據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地址查詢所屬地區內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: