编程语言
首页 > 编程语言> > c# 获取公网IP

c# 获取公网IP

作者:互联网

c# 获取公网IP

引用Nuget包

HtmlAgilityPack

 

根据HtmlAgilityPack 获取公网IP

        /// <summary>
        /// 获取本地电脑公网IP
        /// </summary>
        /// <returns></returns>
        public static string GetExtranetIpAddress()
        {
            string ExtranetIp = string.Empty;
            try
            {
                string Url = "https://2021.ip138.com/";
                WebClient webClient = new WebClient();
                webClient.Encoding = UTF8Encoding.UTF8;
                string html = webClient.DownloadString(Url);
                HtmlDocument doc = new HtmlDocument();

                doc.LoadHtml(html);
                //下面的意思是:通过属性id的值,来定位A标签
                IEnumerable<HtmlNode> node = doc.DocumentNode.Descendants("a");
                foreach (var item in node)
                {
//获取A标签html文本 ExtranetIp = item.InnerText; break; } } catch { ExtranetIp = ""; } return ExtranetIp; }

 

标签:string,c#,IP,html,公网,ExtranetIp,webClient
来源: https://www.cnblogs.com/zhuiguangzheeee/p/15701369.html