這種方式效率不算高,如果用在WEB中,如果用得少可以用這種方式,如果常用,還是建議用IP庫
復制代碼 代碼如下:
#region##得到真實IP以及所在地詳細信息
///<summary>
/// 得到真實IP以及所在地詳細信息(Porschev)
///</summary>
///<returns></returns>
public string GetIpDetails()
{
string url = "http://www.ip138.com/ips8.asp"; //設置獲取IP地址和國家源碼的網址
string regStr = "(?<=<td\\s*align=\\\"center\\\">)[^<]*?(?=<br/><br/></td>)";
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; //IP地址
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 = ma.Value; //得到IP
int index = html.LastIndexOf(":") + 1;
country = html.Substring(index); //得到國家
adr = GetAdrByIp(ip);
return "IP:" + ip + " 國家:" + country + " 省市:" + adr;
}
#endregion
#region##通過IP得到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];
}
#endregion
#region##獲取HTML源碼信息
///<summary>
/// 獲取HTML源碼信息(Porschev)
///</summary>
///<param name="url">獲取地址</param>
///<returns>HTML源碼</returns>
public string GetHtml(string url)
{
Uri uri = new Uri(url);
WebRequest wr = WebRequest.Create(uri);
Stream s = wr.GetResponse().GetResponseStream();
StreamReader sr = new StreamReader(s, Encoding.Default);
return sr.ReadToEnd();
}
#endregion