'Finding a public facing IP address in Python?

How can I find the public facing IP for my net work in Python?



Solution 1:[1]

https://api.ipify.org/?format=json is pretty straight forward

can be parsed by just running requests.get("https://api.ipify.org/?format=json").json()['ip']

Solution 2:[2]

whatismyip.org is better... it just tosses back the ip as plaintext with no extraneous crap.

import urllib
ip = urllib.urlopen('http://whatismyip.org').read()

But yeah, it's impossible to do it easily without relying on something outside the network itself.

Solution 3:[3]

import requests
r = requests.get(r'http://jsonip.com')
# r = requests.get(r'https://ifconfig.co/json')
ip= r.json()['ip']
print('Your IP is {}'.format(ip))

Reference

Solution 4:[4]

If you don't mind expletives then try:

http://wtfismyip.com/json

Bind it up in the usual urllib stuff as others have shown.

There's also:

http://www.networksecuritytoolkit.org/nst/tools/ip.php

Solution 5:[5]

import urllib2
text = urllib2.urlopen('http://www.whatismyip.org').read()
urlRE=re.findall('[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}',text)
urlRE        

['146.148.123.123']

Try putting whatever 'findmyipsite' you can find into a list and iterating through them for comparison. This one seems to work well.

Solution 6:[6]

This is simple as

>>> import urllib
>>> urllib.urlopen('http://icanhazip.com/').read().strip('\n')
'xx.xx.xx.xx'

Solution 7:[7]

You can also use DNS which in some cases may be more reliable than http methods:

#!/usr/bin/env python3

import dns.resolver

resolver1_opendns_ip = False
resolver = dns.resolver.Resolver()
opendns_result = resolver.resolve("resolver1.opendns.com", "A")
for record in opendns_result:
    resolver1_opendns_ip = record.to_text()

if resolver1_opendns_ip:
    resolver.nameservers = [resolver1_opendns_ip]
    myip_result = resolver.resolve("myip.opendns.com", "A")
    for record in myip_result:
        print(f"Your external ip is {record.to_text()}")

This is the python equivalent of dig +short -4 myip.opendns.com @resolver1.opendns.com

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 twig
Solution 2 Steve Losh
Solution 3 Abhijeet
Solution 4 powlo
Solution 5 Arch Angeles
Solution 6 loretoparisi
Solution 7 htaccess