亲测,复制到项目中,可以直接使用。
调用:
//获取当前公网IP 以及地址
Dictionary<string, string> LocationName = new Dictionary<string, string>();
LocationName = GetLocation();
///
/// 获取页面html
///
/// 请求的地址
/// 编码方式
///
public static string GetHtml(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 “访问 " + url + " 失败,请检查网络配置”;
}
return pageHtml;
}
/// <summary>
/// 从html中通过正则找到ipv4信息
/// </summary>
/// <param name="pageHtml"></param>
/// <returns></returns>
public static string GetGlobalIP()
{
string pageHtml = GetHtml("http://www.net.cn/static/customercare/yourip.asp", "gbk");
//验证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 = "none";
Match m = Regex.Match(pageHtml, reg);
if (m.Success)
{
ip = m.Value;
}
Console.WriteLine("公网ip:"+ip);
return ip;
}
/// <summary>
/// 根据IP地址获取城市信息
/// </summary>
/// <returns></returns>
public static Dictionary<string,string> GetLocation()
{
//string ip = "112.17.30.75";
string ip = GetGlobalIP();
string html = GetHtml("https://www.ip138.com/iplookup.asp?ip=" + ip + "&action=2", "gb2312");
//Console.WriteLine(html);
string pre = "var ip_result = {\"ASN归属地\":\"";
int pos = html.IndexOf(pre);
html = html.Substring(pos + pre.Length);
html = html.Substring(0, html.IndexOf('"'));
Console.WriteLine(html);
// 变为"浙江省杭州市 移动 "
string []res = html.Split(new char[] { '省', '市', ' ' },StringSplitOptions.RemoveEmptyEntries);
foreach(var s in res)
{
Console.WriteLine(s);
}
var M = new Dictionary<string, string>();
M["省"] = res[0];
M["市"] = res[1];
M["运营商"] = res[2];
return M;
}
/// <summary>
/// 获取本地IP地址
/// </summary>
/// <returns></returns>
public static string GetIP()
{
string res = "";
IPAddress[] addres = Dns.GetHostAddresses(Dns.GetHostName());
foreach (var ip in addres)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
res += ip.ToString() + " ";
}
}
Console.WriteLine(res);
return res;
}
————————————————
感谢原文博主提供的方法
原文链接:https://blog.csdn.net/jk_chen_acmer/article/details/109531611