How to get external IP using Python



Hello,

Today we're going to see how to get our external IP within a Python script

One of the easiest ways is to use the websites that provides your external IP and use any library like urllib2 (Python 2.7) or urllib (Python 3) to read this page.

PYTHON 2.7

def get_external_IP():
    ''' Get external IP using some websites '''
    import urllib2
    import re  
    import random
 
    counter = 0
    response_ip = []
 
    # This is the list of the pages we will try to use to get our external IP
    ip_websites = ['http://www.canyouseeme.org/', 'http://checkip.dyndns.org/', ]
 
    # We try to get the external IP 10 times
    while not response_ip and counter < 10:
        # Read one random page from the page list
        site = urllib2.urlopen(random.choice(ip_websites)).read() 
 
        # Use regex to find our IP in the response of the page
        regex_ip = '([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})'
        response_ip = re.findall(regex_ip, site)  
        counter += 1
 
    if counter == 10:  # If the counter value is 10 here, it doesn't found the IP
        print("Can't obtain external IP fro the pages, Are you connected to internet ?")
        sys.exit(2)
 
    address = response_ip[0]
    return address

This function would return us our external IP. This is an easy method to get our external IP without complications.

PYTHON 3.0+

def get_external_IP():
    ''' Get external IP using some websites '''
    import urllib.request 
    import re  
    import random
 
    counter = 0
    response_ip = []
 
    # This is the list of the pages we will try to use to get our external IP
    ip_websites = ['http://www.canyouseeme.org/', 'http://checkip.dyndns.org/',]
    
    # We try to get the external IP 10 times
    while not response_ip and counter < 10:
        # Read one random page from the page list
        site = urllib.request.urlopen(random.choice(ip_websites)).read() 
 
        # Use regex to find our IP in the response of the page
        regex_ip = '([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})'
        response_ip = re.findall(regex_ip, site.decode("utf-8"))  
        counter += 1
 
    if counter == 10:  # If the counter value is 10 here, it doesn't found the IP
        print("Can't obtain external IP fro the pages, Are you connected to internet ?")
        sys.exit(2)
 
    address = response_ip[0]
    return address

This function would return us our external IP. This is an easy method to get our external IP without complications.

Any doubt don't hesitate commenting !

Leave a comment

You have to wait to comment again. Wait Time: