Skip to content

Instantly share code, notes, and snippets.

@SeanPesce
Last active May 20, 2025 11:55
Show Gist options
  • Save SeanPesce/1e8877011dd8332c676b99353ae5e2c9 to your computer and use it in GitHub Desktop.
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
#!/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