JohnKlann / python

Python: How to get external IP address

Here is a short simple way to get the external ip address of a machine using python. This of course is useful if your machine is sitting behind a router or a sub network. So unfortunately there is no one liner in python to grab your external ip address which means a third party service must be used. However you can be your own “third party” service if you own a website. (If you don’t you can always use mine!)

Step 1:

Create a php file called getmyip.php you will want to include the following code:


$ipaddress = $_SERVER["REMOTE_ADDR"];

Echo "Your IP is $ipaddress!";


Upload this to your website and mark the location.

Step 2:

Create a python file called you will want to include the following code:

import urllib

import re

def get_external_ip():
site = urllib.urlopen("").read() #if you want to use my website the url is:
ip=re.findall(r'[0-9]+(?:\.[0-9]+){3}', site)
address = ip[0]
print address
return address


Then just execute the python script.

You can find the source here