概述
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#根据IP地址查询所属地区实例详解的全部内容,希望文章能够帮你解决C#根据IP地址查询所属地区实例详解所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复