Get public/external IP address?

前端 未结 26 2243
鱼传尺愫
鱼传尺愫 2020-11-22 14:32

I cant seem to get or find information on finding my routers public IP? Is this because it cant be done this way and would have to get it from a website?

26条回答
  •  臣服心动
    2020-11-22 14:53

    I've refactored @Academy of Programmer's answer to shorter code and altered it so that it only hits https:// URLs:

        public static string GetExternalIPAddress()
        {
            string result = string.Empty;
    
            string[] checkIPUrl =
            {
                "https://ipinfo.io/ip",
                "https://checkip.amazonaws.com/",
                "https://api.ipify.org",
                "https://icanhazip.com",
                "https://wtfismyip.com/text"
            };
    
            using (var client = new WebClient())
            {
                client.Headers["User-Agent"] = "Mozilla/4.0 (Compatible; Windows NT 5.1; MSIE 6.0) " +
                    "(compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
    
                foreach (var url in checkIPUrl)
                {
                    try
                    {
                        result = client.DownloadString(url);
                    }
                    catch
                    {
                    }
    
                    if (!string.IsNullOrEmpty(result))
                        break;
                }
            }
    
            return result.Replace("\n", "").Trim();
        }
    }
    

提交回复
热议问题