C#获取外网IP

 public static string getExternalIp()
        {
            try
            {
                WebClient client = new WebClient();
                client.Encoding = System.Text.Encoding.Default;
                //string response = client.DownloadString("http://1212.ip138.com/ic.asp");//失效了
                //string response = client.DownloadString("http://icanhazip.com/");//可用,可能不稳定
                string response = client.DownloadString("http://ip.chinaz.com/");//站长之家
                string myReg = @"<dd class=""fz24"">([\s\S]+?)<\/dd>";
                Match mc = Regex.Match(response, myReg, RegexOptions.Singleline);
                if (mc.Success && mc.Groups.Count > 1)
                {
                    response = mc.Groups[1].Value;
                    return response;
                }
                else
                {
                    return "Can't get you Ip address!";
                }
            }
            catch (Exception)
            {
                return "Can't get you Ip address!";
            }

        }



        //获取宽带连接(PPPOE拨号)的IP地址,timeout超时(秒),当宽带未连接或者连接中的时候获取不到IP
        public static string GetIP_PPPOE(int timeout)
        {
            int i = timeout * 2;
            while (i > 0)
            {
                try
                {
                    NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
                    bool havePPPOE = false;
                    foreach (NetworkInterface adapter in nics)
                    {
                        if (adapter.NetworkInterfaceType == NetworkInterfaceType.Ppp)
                        {
                            havePPPOE = true;
                            IPInterfaceProperties ip = adapter.GetIPProperties();     //IP配置信息
                            if (ip.UnicastAddresses.Count > 0)
                            {
                                return ip.UnicastAddresses[0].Address.ToString();
                            }
                        }
                    }
                    //当没有宽带连接的时候直接返回空
                    if (!havePPPOE) return "";
                }
                catch (Exception ex)
                {
                    Console.WriteLine("获取宽带拨号IP出错:" + ex.Message);
                }
                i--;
                Thread.Sleep(500);
            }
            return "";
        }

猜你喜欢

转载自blog.csdn.net/qq_39774060/article/details/80558407