首页 > 其他 > 详细

获取本机外网ip和内网ip

时间:2016-06-28 20:25:32      阅读:256      评论:0      收藏:0      [点我收藏+]

  获取本机外网ip

 1   //获取本机的公网IP
 2         public static string GetIP()
 3         {
 4             string tempip = "";
 5             try
 6             {
 7                 WebRequest request = WebRequest.Create("http://ip.qq.com/");
 8                 request.Timeout = 10000;
 9                 WebResponse response = request.GetResponse();
10                 Stream resStream = response.GetResponseStream();
11                 StreamReader sr = new StreamReader(resStream, System.Text.Encoding.Default);
12                 string htmlinfo = sr.ReadToEnd();
13                 //匹配IP的正则表达式
14                 Regex 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);
15                 Match mc = r.Match(htmlinfo);
16                 //获取匹配到的IP
17                 tempip = mc.Groups[0].Value;
18 
19                 resStream.Close();
20                 sr.Close();
21             }
22             catch (Exception err)
23             {
24                 tempip = err.Message;
25             }
26             return tempip;
27         }

 

获取本机内网ip

 //获取内网IP
        private string GetInternalIP()
        {
            IPHostEntry host;
            string localIP = "?";
            host = Dns.GetHostEntry(Dns.GetHostName());
            foreach (IPAddress ip in host.AddressList)
            {
                if (ip.AddressFamily.ToString() == "InterNetwork")
                {
                    localIP = ip.ToString();
                    break;
                }
            }
            return localIP;
        }

 

获取本机外网ip和内网ip

原文:http://www.cnblogs.com/webwang/p/5624672.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!