How do I get the external IP of a socket in Python?

This isn't possible without cooperation from an external server, because there could be any number of NATs between you and the other computer. If it's a custom protocol, you could ask the other system to report what address it's connected to.


https://github.com/bobeirasa/mini-scripts/blob/master/externalip.py

'''
Finds your external IP address
'''

import urllib
import re

def get_ip():
    group = re.compile(u'(?P<ip>\d+\.\d+\.\d+\.\d+)').search(urllib.URLopener().open('http://jsonip.com/').read()).groupdict()
    return group['ip']

if __name__ == '__main__':
    print get_ip()

You'll need to use an external system to do this.

DuckDuckGo's IP answer will give you exactly what you want, and in JSON!

import requests

def detect_public_ip():
    try:
        # Use a get request for api.duckduckgo.com
        raw = requests.get('https://api.duckduckgo.com/?q=ip&format=json')
        # load the request as json, look for Answer.
        # split on spaces, find the 5th index ( as it starts at 0 ), which is the IP address
        answer = raw.json()["Answer"].split()[4]
    # if there are any connection issues, error out
    except Exception as e:
        return 'Error: {0}'.format(e)
    # otherwise, return answer
    else:
        return answer

public_ip = detect_public_ip()
print(public_ip)

The only way I can think of that's guaranteed to give it to you is to hit a service like http://whatismyip.com/ to get it.

Tags:

Python

Sockets