c#通过ip获取地理信息
程序员文章站
2023-12-21 11:48:40
复制代码 代码如下:/// /// 通过ip得到ip所在地省市(porschev...
复制代码 代码如下:
/// <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;
}