获取本机外网ip和内网ip

Posted webWang-web王

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了获取本机外网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;
        }

 

以上是关于获取本机外网ip和内网ip的主要内容,如果未能解决你的问题,请参考以下文章

C#程序怎么获得外网IP和内网IP?

java中如何获取到本机的外网ip地址?

怎么判断自己ip是内网还是外网

想让笔记本同时访问外网和内网,该怎么设置ip

获取本机公网ip(public ip)

内网WEB服务器IP如何映射到外网