Get public/external IP address?

Viewed 190209

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?

27 Answers

I find most of the other answers lacking as they assume that any returned string must be the IP, but doesn't really check for it. This is my solution that I'm currently using. It will only return a valid IP or null if none is found.

public class WhatsMyIp
{
    public static IPAddress PublicIp { get; private set; }
    static WhatsMyIp()
    {
        PublicIp = GetMyIp();
    }

    public static IPAddress GetMyIp()
    {
        List<string> services = new List<string>()
        {
            "https://ipv4.icanhazip.com",
            "https://api.ipify.org",
            "https://ipinfo.io/ip",
            "https://checkip.amazonaws.com",
            "https://wtfismyip.com/text",
            "http://icanhazip.com"
        };
        using (var webclient = new WebClient())
            foreach (var service in services)
            {
                try { return IPAddress.Parse(webclient.DownloadString(service)); } catch { }
            }
        return null;
    }
}

Answers based on using external web services are not exactly correct, because they do not actually answer the stated question:

... information on finding my routers public IP


Explanation

All online services return the external IP address, but it does not essentially mean, that this address is assigned to the user's router.

Router may be assigned with another local IP address of ISP infrastructure networks. Practically this means, that router can not host any services available on Internet. This may be good for safety of most home users, but not good for geeks who host servers at home.

Here's how to check if router has external IP:

trace route to web server behind ISP

According to Wikipedia article, the IP address ranges 10.0.0.0 – 10.255.255.255, 172.16.0.0 – 172.31.255.255 and 192.168.0.0 – 192.168.255.255 are used for private i.e. local networks.

See what happens when you trace route to some remote host with router being assigned with external IP address:

trace route to web server with external IP address

Gotcha! First hop starts from 31.* now. This clearly means that there's nothing between your router and Internet.


Solution

  1. Make Ping to some address with Ttl = 2
  2. Evaluate where response comes from.

TTL=2 must be not enough to reach remote host. Hop #1 host will emit "Reply from <ip address>: TTL expired in transit." revealing its IP address.

Implementation

try
{
    using (var ping = new Ping())
    {
        var pingResult = ping.Send("google.com");
        if (pingResult?.Status == IPStatus.Success)
        {
            pingResult = ping.Send(pingResult.Address, 3000, "ping".ToAsciiBytes(), new PingOptions { Ttl = 2 });

            var isRealIp = !Helpers.IsLocalIp(pingResult?.Address);

            Console.WriteLine(pingResult?.Address == null
                ? $"Has {(isRealIp ? string.Empty : "no ")}real IP, status: {pingResult?.Status}"
                : $"Has {(isRealIp ? string.Empty : "no ")}real IP, response from: {pingResult.Address}, status: {pingResult.Status}");

            Console.WriteLine($"ISP assigned REAL EXTERNAL IP to your router, response from: {pingResult?.Address}, status: {pingResult?.Status}");
        }
        else
        {
            Console.WriteLine($"Your router appears to be behind ISP networks, response from: {pingResult?.Address}, status: {pingResult?.Status}");
        }
    }
}
catch (Exception exc)
{
    Console.WriteLine("Failed to resolve external ip address by ping");
}

Small helper is used to check if IP belongs to private or public network:

public static bool IsLocalIp(IPAddress ip) {
    var ipParts = ip.ToString().Split(new [] { "." }, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToArray();

    return (ipParts[0] == 192 && ipParts[1] == 168) 
        || (ipParts[0] == 172 && ipParts[1] >= 16 && ipParts[1] <= 31) 
        ||  ipParts[0] == 10;
}

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();
    }
}

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<String> hosts = new List<String>();
        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;
    }

WebClient, WebRequest and many other are obsolete, consider using it:

public static IPAddress? GetExternalIP ()
{
    try
    {
        using (var client = new HttpClient())
            return IPAddress.Parse(client.GetAsync("http://ipinfo.io/ip").Result.Content.ReadAsStringAsync().Result);
    }
    catch (Exception ex)
    {
        return null;
    }
}
Related