43 lines
1.4 KiB
Python
43 lines
1.4 KiB
Python
#!/usr/bin/env python3
|
|
"""Resolve this host's public IP so the viewer can hide operator traffic.
|
|
|
|
Loopback/private addresses are ignored. Use `--loop --interval 1800` to run it as a
|
|
30-minute refresher; the viewer imports discover() directly and refreshes itself.
|
|
"""
|
|
import argparse
|
|
import ipaddress
|
|
import time
|
|
import urllib.request
|
|
|
|
ENDPOINTS = ('https://api.ipify.org', 'https://ifconfig.me/ip',
|
|
'https://icanhazip.com', 'https://1.1.1.1/cdn-cgi/trace')
|
|
|
|
|
|
def discover(timeout=6):
|
|
for url in ENDPOINTS:
|
|
try:
|
|
with urllib.request.urlopen(url, timeout=timeout) as response:
|
|
text = response.read(256).decode('utf-8', 'replace')
|
|
except (OSError, ValueError):
|
|
continue
|
|
for token in text.replace('ip=', ' ').split():
|
|
try:
|
|
ip = ipaddress.ip_address(token.strip())
|
|
except ValueError:
|
|
continue
|
|
if ip.is_global:
|
|
return str(ip)
|
|
return None
|
|
|
|
|
|
if __name__ == '__main__':
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument('--loop', action='store_true', help='keep refreshing')
|
|
parser.add_argument('--interval', type=int, default=1800)
|
|
args = parser.parse_args()
|
|
while True:
|
|
print(discover() or '', flush=True)
|
|
if not args.loop:
|
|
break
|
|
time.sleep(args.interval)
|