Created
January 17, 2024 18:35
-
-
Save nickovs/5667a477b618b63e6ba5bf16f1c8cc1c to your computer and use it in GitHub Desktop.
A tool for fetching your current public IPv4 address
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 | |
from random import shuffle | |
from sys import exit, stderr | |
from urllib.request import urlopen | |
from urllib.error import URLError | |
urls = [ | |
"ifconfig.me", | |
"icanhazip.com", | |
"ipinfo.io/ip", | |
"api.ipify.org", | |
"ident.me", | |
"bot.whatismyipaddress.com", | |
"ipecho.net/plain", | |
"checkip.amazonaws.com", | |
"whatismyip.akamai.com", | |
"diagnostic.opendns.com/myip", | |
] | |
def fetch_ip_address(): | |
shuffled_urls = list(urls) | |
shuffle(shuffled_urls) | |
while shuffled_urls: | |
target = shuffled_urls.pop() | |
try: | |
r = urlopen("http://" + target, timeout=3) | |
if r.status == 200: | |
return r.read().strip().decode("ASCII") | |
except URLError as e: | |
pass | |
else: | |
return None | |
if __name__ == "__main__": | |
result = fetch_ip_address() | |
if result: | |
print(result) | |
else: | |
print("No address could be found", file=stderr) | |
exit(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment