码迷,mamicode.com
首页 > 其他好文 > 详细

获取本机外网ip和内网ip

时间:2016-06-28 20:27:45      阅读:138      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!