Top
JohnKlann / networking  / Python: How to get external IP address

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:

<?php

$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 my_external_ip.py you will want to include the following code:

import urllib

import re

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

get_external_ip()

Then just execute the python script.

You can find the source here

Submit your review
1
2
3
4
5
Submit
     
Cancel

Create your own review

Average rating:  
 0 reviews