void Main()
{
var t0_html = HttpGetPageHtml("https://tool.lu/ip/", "utf-8");
var t1_html = HttpGetPageHtml("http://www.ip111.cn/", "utf-8");
var t2_html = HttpGetPageHtml("http://www.882667.com/", "utf-8");
var t0_ip = GetIPFromHtml(t0_html).Dump("https://tool.lu/ip/");//
var t1_ip = GetIPFromHtml(t1_html).Dump("http://www.ip111.cn/");;//
var t2_ip = GetIPFromHtml(t2_html).Dump("http://www.882667.com/");;//
}
/// <summary>
/// 擷取頁面html
/// </summary>
/// <param name="url">請求的位址</param>
/// <param name="encoding">編碼方式</param>
/// <returns></returns>
public static string HttpGetPageHtml(string url, string encoding)
{
string pageHtml = string.Empty;
try
{
using (WebClient MyWebClient = new WebClient())
{
Encoding encode = Encoding.GetEncoding(encoding);
MyWebClient.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.84 Safari/537.36");
MyWebClient.Credentials = CredentialCache.DefaultCredentials;//擷取或設定用于向Internet資源的請求進行身份驗證的網絡憑據
Byte[] pageData = MyWebClient.DownloadData(url); //從指定網站下載下傳資料
pageHtml = encode.GetString(pageData);
}
}
catch (Exception e)
{
}
return pageHtml;
}
/// <summary>
/// 從html中通過正則找到ip資訊(隻支援ipv4位址)
/// </summary>
/// <param name="pageHtml"></param>
/// <returns></returns>
public static string GetIPFromHtml(String pageHtml)
{
//驗證ipv4位址
string reg = @"(?:(?:(25[0-5])|(2[0-4]\d)|((1\d{2})|([1-9]?\d)))\.){3}(?:(25[0-5])|(2[0-4]\d)|((1\d{2})|([1-9]?\d)))";
string ip = "";
Match m = Regex.Match(pageHtml, reg);
if (m.Success)
{
ip = m.Value;
}
return ip;
}
複制