此方法是通过IP查询归属地网站的GET方式,发送请求IP,并使用正则表达式抓取返回的归属地
首先:引用命名空间:
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
第二:代码
/// <summary>
/// 获取IP归属地
/// </summary>
/// <param name="Ip">IP地址</param>
/// <returns></returns>
public string GetIpAddRess(string Ip)
{
WebRequest request = WebRequest.Create("http://www.ip138.com/ips138.asp?ip=" + Ip);
WebResponse response = request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("gb2312"));
string read = reader.ReadToEnd();
Regex regex = new Regex("<td align=\"center\"><ul class=\"ul1\"><li>本站主数据:(?<title>.*?)</li>");
if (regex.IsMatch(read))
{
read = regex.Match(read).Groups["title"].Value;
}
return read;
}
直接调用这个方法就可以了,函数的形参是IP地址形式的字符串,函数返回的是IP归属地的字符串