獲取本機外網ip和內網ip

  獲取本機外網iphtml

 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;
        }
相關文章
相關標籤/搜索