Getting a machine's external IP address with Python

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').text
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.