Last active
May 20, 2025 11:55
-
-
Save SeanPesce/1e8877011dd8332c676b99353ae5e2c9 to your computer and use it in GitHub Desktop.
Python 3 script to obtain the current external IPv4 address without any non-standard dependencies
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# | |
# Author: Sean Pesce | |
import re | |
import requests | |
def get_external_ipv4_address(timeout_secs=0.3): | |
counts = dict() | |
urls = { | |
'https://curlmyip.net/': None, | |
'https://device.payfone.com:4443/whatismyipaddress': None, | |
'https://jsonip.com': 'ip', | |
'https://icanhazip.com/': None, | |
'https://ifconfig.co/json': 'ip', | |
'https://ip-addr.es/': None, | |
'https://myip.dnsomatic.com/': None, | |
'https://wtfismyip.com/text': None, | |
'https://www.networksecuritytoolkit.org/nst/tools/ip.shtml': None, | |
} | |
for url in urls: | |
ip_key = urls[url] | |
try: | |
resp = requests.get(url, timeout=(timeout_secs,timeout_secs), allow_redirects=False) | |
if ip_key: | |
ip = resp.json()[ip_key] | |
else: | |
ip = resp.text | |
ip = ip.lower().strip() | |
if ip not in counts: | |
counts[ip] = 1 | |
else: | |
counts[ip] += 1 | |
except Exception as err: | |
pass | |
# Websites that don't respond with simple data | |
urls = [ | |
'https://meuip.com/', | |
'https://myip.ch/', | |
'https://www.find-ip-address.org/', | |
#'https://www.ipaddresslocation.org/', | |
'https://www.ipinfodb.com/', | |
'https://www.myipaddress.com/', | |
'https://www.showmyipaddress.com/', | |
] | |
for url in urls: | |
try: | |
resp = requests.get(url, timeout=(timeout_secs,timeout_secs), allow_redirects=False) | |
match = re.search('[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}', resp.text) | |
if not match: | |
continue | |
ip = match.group() | |
ip = ip.lower().strip() | |
if ip not in counts: | |
counts[ip] = 1 | |
else: | |
counts[ip] += 1 | |
except Exception as err: | |
pass | |
my_ip = None | |
for ip in counts: | |
if not my_ip: | |
my_ip = ip | |
continue | |
if counts[my_ip] < counts[ip]: | |
my_ip = ip | |
return my_ip | |
if __name__ == '__main__': | |
print(get_external_ipv4_address()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment