Getting a machine's external IP address with Python

Looking for a better way to get a machines current external IP #... Below works, but would rather not rely on an outside site to gather the information ... I am restricted to using standard Python 2.5.1 libraries bundled with Mac OS X 10.5.x

import os
import urllib2

def check_in():

    fqn = os.uname()[1]
    ext_ip = urllib2.urlopen('http://whatismyip.org').read()
    print ("Asset: %s " % fqn, "Checking in from IP#: %s " % ext_ip)

I liked the http://ipify.org. They even provide Python code for using their API.

# This example requires the requests library be installed.  You can learn more
# about the Requests library here: http://docs.python-requests.org/en/latest/
from requests import get

ip = get('https://api.ipify.org').content.decode('utf8')
print('My public IP address is: {}'.format(ip))

Python3, using nothing else but the standard library

As mentioned before, one can use an external service like https://ident.me in order to discover the external IP address of your router.

Here is how it is done with python3, using nothing else but the standard library:

import urllib.request

external_ip = urllib.request.urlopen('https://ident.me').read().decode('utf8')

print(external_ip)

If you are behind a router which obtains the external IP, I'm afraid you have no other option but to use external service like you do. If the router itself has some query interface, you can use it, but the solution will be very environment-specific and unreliable.


You should use the UPnP protocol to query your router for this information. Most importantly, this does not rely on an external service, which all the other answers to this question seem to suggest.

There's a Python library called miniupnp which can do this, see e.g. miniupnpc/testupnpigd.py.

pip install miniupnpc

Based on their example you should be able to do something like this:

import miniupnpc

u = miniupnpc.UPnP()
u.discoverdelay = 200
u.discover()
u.selectigd()
print('external ip address: {}'.format(u.externalipaddress()))

I prefer this Amazon AWS endpoint:

import requests
ip = requests.get('https://checkip.amazonaws.com').text.strip()