获取本机外网ip和内网ip

  获取本机外网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;
        }

 

posted @ 2016-06-28 18:42  web王  阅读(3257)  评论(0编辑  收藏  举报