C#根據(jù)IP地址查詢所屬地區(qū)實例詳解
更新時間:2021年03月06日 16:14:32 作者:祝君圓夢
這篇文章主要介紹了C#根據(jù)IP地址查詢所屬地區(qū)實例詳解,調(diào)用的接口是免費的接口,有需要的同學可以研究下
ip-api.com接口(解析 json需要引入Newtonsoft.Json.dll ):
/// <summary>
/// 根據(jù)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數(shù)據(jù)
string html = sr.ReadToEnd();
//Newtonsoft.Json讀取數(shù)據(jù)
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>
/// 根據(jù)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);
//獲取到的數(shù)據(jù)格式:var lo="江蘇省", lc="鎮(zhèn)江市"; var localAddress={city:"鎮(zhèn)江市", 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#根據(jù)IP地址查詢所屬地區(qū)實例詳解的文章就介紹到這了,更多相關C#根據(jù)IP地址查詢所屬地區(qū)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
C# 實現(xiàn)ADSL自動斷網(wǎng)和撥號的方法(適用于撥號用戶)
下面小編就為大家?guī)硪黄狢# 實現(xiàn)ADSL自動斷網(wǎng)和撥號的方法(適用于撥號用戶)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-12-12
C#實現(xiàn)將TextBox綁定為KindEditor富文本
KindEditor?依靠出色的用戶體驗和領先的技術提供富文本編輯功能,是一款非常受歡迎的HTML在線編輯器,下面我們就來看看C#如何將TextBox綁定為KindEditor富文本吧2024-04-04
C#實現(xiàn)Word轉(zhuǎn)換TXT的方法詳解
這篇文章主要為大家詳細介紹了如何利用C#實現(xiàn)Word轉(zhuǎn)換TXT的功能,文中的示例代碼講解詳細,對我們學習C#有一定的幫助,感興趣的小伙伴可以跟隨小編一起了解一下2022-12-12
C#中parallel.foreach實現(xiàn)多線程處理
Parallel.ForEach方法是C#中的一個并行循環(huán)方法,它可以并行地對一個集合進行迭代操作,本文主要介紹了C#中parallel.foreach實現(xiàn)多線程處理,具有一定的參考價值,感興趣的可以了解一下2024-02-02

