码迷,mamicode.com
首页 > Windows程序 > 详细

C#获取本机的外网IP

时间:2016-07-22 14:27:52      阅读:283      评论:0      收藏:0      [点我收藏+]

标签:

 /// <summary>
        /// 功能:获取本地的外网IP地址
        /// 作者:黄海
        /// 时间:2016-07-22
        /// </summary>
        /// <returns></returns>
        private static string GetPublicIp()
        {
            var urlList = new List<string>
            {
                "http://ip.qq.com/",
                "http://pv.sohu.com/cityjson?ie=utf-8",
                "http://ip.taobao.com/service/getIpInfo2.php?ip=myip"
            };
            var tempip = "";
            foreach (var a in urlList)
            {
                try
                {
                    var req = WebRequest.Create(a);
                    req.Timeout = 20000;
                    var response = req.GetResponse();
                    var resStream = response.GetResponseStream();
                    if (resStream != null)
                    {
                        var sr = new StreamReader(resStream, Encoding.UTF8);
                        var htmlinfo = sr.ReadToEnd();
                        //匹配IP的正则表达式
                        var r = new Regex("((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)\\.){3}(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|[1-9])", RegexOptions.None);
                        var mc = r.Match(htmlinfo);
                        //获取匹配到的IP
                        tempip = mc.Groups[0].Value;
                        resStream.Close();
                        sr.Close();
                        response.Dispose();
                    }
                    return tempip;
                }
                catch (Exception err)
                {
                    Console.WriteLine("当前探测URL:"+a+",错误描述:"+err.ToString());
                }
            }
            return tempip;
        }

 

C#获取本机的外网IP

标签:

原文地址:http://www.cnblogs.com/littlehb/p/5694811.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!