36 lines
865 B
Python
36 lines
865 B
Python
import subprocess
|
|
|
|
SERVERS = [
|
|
("resolver1.opendns.com", "myip.opendns.com"),
|
|
("resolver2.opendns.com", "myip.opendns.com"),
|
|
("resolver3.opendns.com", "myip.opendns.com"),
|
|
("resolver4.opendns.com", "myip.opendns.com"),
|
|
("ns1-1.akamaitech.net", "whoami.akamai.net"),
|
|
]
|
|
|
|
|
|
def get_public_ip():
|
|
for server, host in SERVERS:
|
|
try:
|
|
result = subprocess.run(
|
|
[
|
|
"dig",
|
|
"+short",
|
|
host,
|
|
f"@{server}",
|
|
],
|
|
capture_output=True,
|
|
text=True,
|
|
check=True,
|
|
timeout=5,
|
|
)
|
|
|
|
ip = result.stdout.strip()
|
|
|
|
if ip:
|
|
return ip
|
|
|
|
except Exception:
|
|
pass
|
|
|
|
raise RuntimeError("cannot determine public IP")
|