Tutorial :Discovering public IP programmatically


I'm behind a router, I need a simple command to discover my public ip (instead of googling what's my ip and clicking one the results)

Are there any standard protocols for this? I've heard about STUN but I don't know how can I use it?

P.S. I'm planning on writing a short python script to do it


EDIT: curlmyip.com is no longer available. (thanks maxywb)

Original Post:

As of writing this post, curlmyip.com works. From the command line:

curl curlmyip.com  

It's a third-party website, which may or may not be available a couple years down the road. But for the time being, it seems pretty simple and to the point.


This may be the easiest way. Parse the output of the following commands:

  1. run a traceroute to find a router that is less than 3 hops out from your machine.
  2. run ping with the option to record the source route and parse the output. The first IP address in the recorded route is your public one.

For example, I am on a Windows machine, but the same idea should work from unix too.

> tracert -d www.yahoo.com    Tracing route to www-real.wa1.b.yahoo.com []  over a maximum of 30 hops:      1    <1 ms    <1 ms    <1 ms    2     *        *        *     Request timed out.    3     8 ms     8 ms     9 ms    4     8 ms     8 ms     9 ms    5    10 ms     9 ms     9 ms    6    11 ms    10 ms    10 ms  

The is a Comcast (my provider) router. We can ping that:

> ping -r 9 -n 1    Pinging with 32 bytes of data:    Reply from bytes=32 time=10ms TTL=253      Route: ->    ->    ->     

Voila! The is my public IP.


I have made a program that connects to http://automation.whatismyip.com/n09230945.asp it is is written in D an getting someone else to tell you what they see your ip as is probably the most reliable way:

/*      Get my IP address  */      import tango.net.http.HttpGet;  import tango.io.Stdout;    void main()  {        try        {            auto page = new HttpGet ("http://automation.whatismyip.com/n09230945.asp");            Stdout(cast(char[])page.read);        }        catch(Exception ex)        {            Stdout("An exception occurred");        }  }  

Edit python code should be like:

from urllib import urlopen  print urlopen('http://automation.whatismyip.com/n09230945.asp').read()  


Targeting www.whatsmyip.org is rude. They plea not to do that on the page.

Only a system on the same level of NAT as your target will see the same IP. For instance, your application may be behind multiple layers of NAT (this happens more as you move away from the US, where the glut of IPs are).

STUN is indeed the best method. In general, you should be planning to run a (STUN) server somewhere that you application can ask: do not hard code other people's servers. You have to code to send some specific messages as described in rfc5389.

I suggest a good read of, and related links. http://www.ietf.org/html.charters/behave-charter.html

You may prefer to look at IPv6, and Teredo to make sure that you always have IPv6 access. (Microsoft Vista makes this very easy, I'm told)


Whenever I wanted to do this, I would just scrape whatismyip.org. When you go to the site, it gives you your plain text public IP. Plain and simple.

Just have your script access that site and read the IP.

I don't know if you were implying this in your post or not, but it isn't possible to get your public IP from your own computer. It has to come from an external source.

2013 edit: This site returns an image now instead of text, so it's useless for this purpose.


I like the ipify.org:

  • it's free to use (even programmatically and even heavy traffic)
  • response contains only the IP address without any garbage (no need for parsing)
  • you can also request response in JSON
  • works for both IPv4 and IPv6
  • it's hosted in cloud
  • it's open source
$ curl api.ipify.org    $ curl "api.ipify.org?format=json"  {"ip":""}  


As mentioned by several people, STUN is indeed the proper solution.


If the network has an UpNp server running on the gateway you are able to talk to the gateway and ask it for your outside IP address.


Your simplest way may be to ask some server on the outside of your network.

One thing to keep in mind is that different destinations may see a different address for you. The router may be multihomed. And really that's just where problems begin.


To get your external ip, you could make a dns query to an opendns server with the special hostname "myip.opendns.com":

from subprocess import check_output    ip = check_output(["dig", "+short", "@resolver1.opendns.com",                     "myip.opendns.com"]).decode().strip()  

On Windows, you could try nslookup.

There is no dns module in Python stdlib that would allow to specify custom dns server. You could use third party libraries e.g., Twisted to make the dns query:

from twisted.internet     import task # $ pip install twisted  from twisted.names.client import Resolver  from twisted.python.util  import println    def main(reactor):      opendns_resolvers = [("", 53), ("", 53)]      resolver = Resolver(servers=opendns_resolvers, reactor=reactor)      # use magical hostname to get our public ip      return resolver.getHostByName('myip.opendns.com').addCallback(println)  task.react(main)  

Here's the same using dnspython library:

import dns.resolver # $ pip install dnspython    resolver = dns.resolver.Resolver(configure=False)  resolver.nameservers = ["", ""]  print(resolver.query('myip.opendns.com')[0])  


another cheeky way: if your router has got the option to update it's web IP on DynDNS, you can get your own IP with something like:

IP=`resolveip -s myalias.dyndns-home.com`  


Duck Duck Go gives free access to their API according to their own page here: https://duckduckgo.com/api

Here's the URL you hit if you want your IP address: http://api.duckduckgo.com/?q=my+ip&format=json

That returns a JSON object. The Answer attribute has a human readable string with your ip address in it. Example:

{      ...      "Answer": "Your IP address is ww.xx.yyy.zzz in <a href=\"http://open.mapquest.com/?q=aaaaa(bbbbb)\">aaaaa(bbbbb)</a>"      ...  }  

You could extract the ip address from that string by using split()[4], if you think that it's a safe assumption that this string won't ever change or you're willing to need to periodically fix it.

Alternatively, if you want to have a more future proof method, you could loop over everything returned by split() and return the first item that is an ip address. See here for validating IP addresses: How to validate IP address in Python?


I'm sharing you my method of retrieving a server's public IP address without having to use external APIs (which is a security risk of course)

INTERFACE=`ip route get | grep | cut -d' ' -f5`  HOSTIP=`ifconfig $INTERFACE | grep "inet " | awk -F'[: ]+' '{ print $4 }'`  

Or in python if you prefer:

import subprocess  public_ip = subprocess.check_output(["ifconfig `ip route get | grep | cut -d' ' -f5` | grep \'inet \' | awk -F'[: ]+' '{ print $4 }'"], shell=True)  

It works like this:

  • determines the best interface to reach the google dns server
  • greps public IP from the ifconfig entry for that interface


curl api.infoip.io - full details

curl api.infoip.io/ip - just the ip address

curl api.infoip.io/country - just the country name

... and more of the same

you can view the docs at http://docs.ciokan.apiary.io/

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »