Tuesday, 13 May 2014

Quick Tip - How to find your public IP address using Python

Determining your internal IP address is very easy. Just run the command ifconfig in a terminal, and you get it.

However, that is not the IP that is visible to external websites. To determine your external or public IP address, open a browser and search for "my ip" on Google. Google will show it for you.

But what if you want to get that public IP address in a script? This tutorial will show you how to do that.

There are a lot of websites that have a JSON-based API that can return your public IP address, and other such information. One such website is http://httpbin.org

So, if you visit http://httpbin.org/ip, you will get your public IP address in the following format:
{
  "origin": "2.6.8.2"
}
Now that you know how to get the public IP address, you just need to write a script that can connect to this website, and parse the JSON that it returns. Let us use python for this.
from json import loads
from urllib2 import urlopen

# This line will connect to the website, read its contents
# and parse the JSON output
data = loads(urlopen("http://httpbin.org/ip").read())
print "The public IP is : %s" % data["origin"]
The output will look like,
The public IP is : 2.6.8.2
That is all. This is useful if you are using a proxy, and want to confirm that your public IP address is actually different. Note that if the proxy you are using is not truly anonymous, you will get two or more IP addresses, one of which will be yours, and one that belongs to the proxy server.
Hope you liked this quick tip. Please comment and share.

No comments:

Post a Comment