Skip to content

Instantly share code, notes, and snippets.

@nickovs
Created January 17, 2024 18:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nickovs/5667a477b618b63e6ba5bf16f1c8cc1c to your computer and use it in GitHub Desktop.
Save nickovs/5667a477b618b63e6ba5bf16f1c8cc1c to your computer and use it in GitHub Desktop.
A tool for fetching your current public IPv4 address
#!/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