Get public/external IP address?

185,079

Solution 1

Using C#, With webclient its a short one.

public static void Main(string[] args)
{
    string externalIpString = new WebClient().DownloadString("http://icanhazip.com").Replace("\\r\\n", "").Replace("\\n", "").Trim();
    var externalIp = IPAddress.Parse(externalIpString);

    Console.WriteLine(externalIp.ToString());
}

Command Line (works on both Linux and Windows)

wget -qO- http://bot.whatismyipaddress.com

OR

curl http://ipinfo.io/ip

Solution 2

static void Main(string[] args)
{
    HTTPGet req = new HTTPGet();
    req.Request("http://checkip.dyndns.org");
    string[] a = req.ResponseBody.Split(':');
    string a2 = a[1].Substring(1);
    string[] a3=a2.Split('<');
    string a4 = a3[0];
    Console.WriteLine(a4);
    Console.ReadLine();
}

Do this small trick with Check IP DNS

Use HTTPGet class i found on Goldb-Httpget C#

Solution 3

With .Net WebRequest:

  public static string GetPublicIP()
    {
        string url = "http://checkip.dyndns.org";
        System.Net.WebRequest req = System.Net.WebRequest.Create(url);
        System.Net.WebResponse resp = req.GetResponse();
        System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());
        string response = sr.ReadToEnd().Trim();
        string[] a = response.Split(':');
        string a2 = a[1].Substring(1);
        string[] a3 = a2.Split('<');
        string a4 = a3[0];
        return a4;
    }

Solution 4

string pubIp =  new System.Net.WebClient().DownloadString("https://api.ipify.org");

Solution 5

Using a great similar service

private string GetPublicIpAddress()
{
    var request = (HttpWebRequest)WebRequest.Create("http://ifconfig.me");

    request.UserAgent = "curl"; // this will tell the server to return the information as if the request was made by the linux "curl" command

    string publicIPAddress;

    request.Method = "GET";
    using (WebResponse response = request.GetResponse())
    {
        using (var reader = new StreamReader(response.GetResponseStream()))
        {
            publicIPAddress = reader.ReadToEnd();
        }
    }

    return publicIPAddress.Replace("\n", "");
}
Share:
185,079

Related videos on Youtube

arbme
Author by

arbme

Updated on May 12, 2022

Comments

  • arbme
    arbme about 2 years

    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?

    • Alex S
      Alex S almost 14 years
      Which way is "this way"? Are you trying to do this programmatically?
    • Ron Maupin
      Ron Maupin about 4 years
      With CGN, it is possible that your router does not have a public address.
  • Noldorin
    Noldorin almost 14 years
    No worries. I only say because often new members are not familiar with the system... thanks.
  • MsBao
    MsBao about 10 years
    404 on the second one.
  • Nicholas Miller
    Nicholas Miller almost 10 years
    Great answer! By the way, I had to call Trim() on the result from http://ipinfo.io/ip. There was a trailing space.
  • Robert
    Robert about 9 years
    Could you add some commentary?
  • Reg Edit
    Reg Edit almost 9 years
    For NATUPNPLib to work requires UPnP to be enabled in the router, which is a security issue.
  • ElektroStudios
    ElektroStudios over 8 years
    It don't works. ServerVariables member throws a null reference exception.
  • thepirat000
    thepirat000 over 7 years
    that cannot fail! :)
  • Niklas
    Niklas about 7 years
    for some reason the GetStringAsync() as u used it here is much faster for me using a HttpClient rather than a Get Request using WebRequest. i can confirm that this works like a charm.
  • AFract
    AFract almost 7 years
    This seems to be code to find REMOTE client ip, not YOUR client public ip.
  • Emanuel Pirovano
    Emanuel Pirovano over 6 years
    This is the best way, it works and it is short code !
  • Emanuel Pirovano
    Emanuel Pirovano over 6 years
    Great, this is the best way
  • yurenchen
    yurenchen over 6 years
    ifconfig.me this domain is perfect
  • mjb
    mjb over 5 years
    thanks for the sharing. I have included your code in this article: codeproject.com/Tips/1267882/…
  • Paul
    Paul over 5 years
    This will get the server's IP address instead of the user's.
  • MadKonst
    MadKonst about 5 years
    Great solution, however, it depends on some other external service. Would be great to find a couple other similar services and use as a fallback. E.g. api.ipify.org and trackip.net/ip
  • Marcelo Vieira
    Marcelo Vieira about 4 years
    private string GetPublicIpAddress() { using var client = new WebClient(); return client.DownloadString("ifconfig.me").Replace("\n", ""); }
  • Marinos An
    Marinos An about 4 years
    +1 for adding the https in front. I don't know why most people in here consider normal to ask for external ip through http. By the way checkip.amazonaws.com supports ssl now.
  • Ron Maupin
    Ron Maupin almost 4 years
    That does not actually work to get the router address if the ISP is using CGN. It would only get the ISP router address.
  • Ron Maupin
    Ron Maupin almost 4 years
    That does not actually work to get the router address if the ISP is using CGN (becoming more common). It would only get the ISP router address, not the address assigned to your router.
  • Jesper
    Jesper almost 4 years
    @RonMaupin Nobody is talking about the actual router address. The question is what is your IP on the Internet.
  • Kiquenet
    Kiquenet almost 4 years
    HttpGet does not exist , alternative ?
  • ossentoo
    ossentoo about 3 years
    when does this ever exist, with that while loop?
  • Stewart
    Stewart over 2 years
    What's the benefit of parsing the IP address, rather than outputting externalIpString directly?
  • sinsedrix
    sinsedrix about 2 years
    I only get local IPs this way :|
  • absoluteAquarian
    absoluteAquarian about 2 years
    A more up-to-date alternative: public static string GetPublicIPv4Address() => new System.Net.Http.HttpClient().GetStringAsync("http://ifconfig‌​.me").GetAwaiter().G‌​etResult().Replace("‌​\n", "");