Get public/external IP address?

前端 未结 26 2223
鱼传尺愫
鱼传尺愫 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:57

    I had almost the same as Jesper, only I reused the webclient and disposed it correctly. Also I cleaned up some responses by removing the extra \n at the end.

    
        private static IPAddress GetExternalIp () {
          using (WebClient client = new WebClient()) {
            List hosts = new List();
            hosts.Add("https://icanhazip.com");
            hosts.Add("https://api.ipify.org");
            hosts.Add("https://ipinfo.io/ip");
            hosts.Add("https://wtfismyip.com/text");
            hosts.Add("https://checkip.amazonaws.com/");
            hosts.Add("https://bot.whatismyipaddress.com/");
            hosts.Add("https://ipecho.net/plain");
            foreach (String host in hosts) {
              try {
                String ipAdressString = client.DownloadString(host);
                ipAdressString = ipAdressString.Replace("\n", "");
                return IPAddress.Parse(ipAdressString);
              } catch {
              }
            }
          }
          return null;
        }
    
    

提交回复
热议问题