C# 根據ip擷取城市等相關資訊

來源:互聯網
上載者:User

複製代碼 代碼如下:/// <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;
}
/// <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;
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.