c#經由過程ip獲得地輿信息。本站提示廣大學習愛好者:(c#經由過程ip獲得地輿信息)文章只能為提供參考,不一定能成為您想要的結果。以下是c#經由過程ip獲得地輿信息正文
/// <summary>
/// 經由過程IP獲得IP地點地省市(Porschev)
/// </summary>
/// <param name="ip"></param>
/// <returns></returns>
public string GetAdrByIp(string ip)
{
string url = "http://www.cz88.net/ip/?ip=" + ip;
string regStr = "(?<=<span\\s*id=\\\"cz_addr\\\">).*?(?=</span>)";
//獲得網頁源碼
string html = GetHtml(url);
Regex reg = new Regex(regStr, RegexOptions.None);
Match ma = reg.Match(html);
html = ma.Value;
string[] arr = html.Split(' ');
return arr[0];
}
/// <summary>
/// 獲得HTML源碼信息(Porschev)
/// </summary>
/// <param name="url">獲得地址</param>
/// <returns>HTML源碼</returns>
public string GetHtml(string url)
{
string str = "";
try
{
Uri uri = new Uri(url);
WebRequest wr = WebRequest.Create(uri);
Stream s = wr.GetResponse().GetResponseStream();
StreamReader sr = new StreamReader(s, Encoding.Default);
str = sr.ReadToEnd();
}
catch (Exception e)
{
}
return str;
}
/// <summary>
/// 獲得真實IP和地點地具體信息(Porschev)
/// </summary>
/// <returns></returns>
public string GetIpDetails()
{
//設置獲得IP地址和國度源碼的網址
string url = "http://www.ip138.com/ips8.asp";
string regStr = "(?<=<td\\s*align=\\\"center\\\">)[^<]*?(?=<br/><br/></td>)";
//IP正則
string ipRegStr = "((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)";
//IP地址
string ip = string.Empty;
//國度
string country = string.Empty;
//省市
string adr = string.Empty;
//獲得網頁源碼
string html = GetHtml(url);
Regex reg = new Regex(regStr, RegexOptions.None);
Match ma = reg.Match(html); html = ma.Value;
Regex ipReg = new Regex(ipRegStr, RegexOptions.None);
ma = ipReg.Match(html);
//獲得IP
ip = ma.Value;
int index = html.LastIndexOf(":") + 1;
//獲得國度
country = html.Substring(index);
adr = GetAdrByIp(ip);
return "IP:" + ip + " 國度:" + country + " 省市:" + adr;
}