获取本机的公网和私网IP

采用链式处理,先尝试获取公网IP,获取不到时再尝试获取内网IP,再获取不到时赋给默认值。

//获取本机的公网和私网IP
        private string GetIP()
        {
            List<string> urls = new List<string>() 
            { 
             "http://bot.whatismyipaddress.com/",
            "http://ipinfo.io/ip",
            "https://canihazip.com/s",
            "http://icanhazip.com"
            };
            
            string tempip = "";
            try
            {
                foreach (var ipurl in urls)
                {
                    try
                    {
                        WebRequest request = WebRequest.Create("http://icanhazip.com");
                        request.Timeout = 10000;
                        WebResponse response = request.GetResponse();
                        Stream resStream = response.GetResponseStream();
                        StreamReader sr = new StreamReader(resStream, System.Text.Encoding.Default);
                        string htmlinfo = sr.ReadToEnd();
                        //匹配IP的正则表达式
                        System.Text.RegularExpressions.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);
                        Match mc = r.Match(htmlinfo);
                        //获取匹配到的IP
                        tempip = mc.Groups[0].Value;

                        resStream.Close();
                        sr.Close();
                        break;
                    }
                    catch
                    {
                        
                    }
                }
                return tempip;
            }
            catch
            {
                SendLog("获取当前设备的公网IP失败,尝试获取当前设备的私网IP");
                try
                {
                    return GetLocalIPAddress();
                }
                catch
                {
                    SendLog("获取当前设备的私网IP失败,赋予默认值127.0.0.1");
                    return "127.0.0.1";
                }
            }
        }

        #region GetLocalIP
        private string GetLocalIPAddress()
        {
            var host = Dns.GetHostEntry(Dns.GetHostName());
            foreach (var ip in host.AddressList)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    return ip.ToString();
                }
            }
            throw new Exception("No network adapters with an IPv4 address in the system!");
        }

猜你喜欢

转载自blog.csdn.net/u010178308/article/details/86184787
今日推荐