apppublic/appPublic/uni_outip.py

71 lines
1.3 KiB
Python
Raw Normal View History

2023-06-24 18:17:18 +08:00
import os
2023-06-24 17:41:17 +08:00
import time
from natpmp import NATPMP as pmp
import upnpclient
2023-06-24 18:17:18 +08:00
from appPublic.ipgetter import IPgetter
from multiprocessing import Process, Pipe
2023-06-24 17:41:17 +08:00
def pmp_get_external_ip():
2023-06-25 10:35:31 +08:00
try:
return pmp.get_public_address()
except:
return None
2023-06-24 17:41:17 +08:00
def upnp_get_external_ip():
2023-06-25 10:35:31 +08:00
try:
igd = upnpclient.discover()[0]
2023-06-28 15:21:24 +08:00
print(igd.service_map)
2023-06-25 10:35:31 +08:00
s_names = [ n for n in igd.service_map.keys() if 'WAN' in n and 'Conn' in n]
upnp = igd.service_map[s_names[0]]
x = upnp.GetExternalIPAddress()
return x.get('NewExternalIPAddress', None)
2023-06-28 15:21:24 +08:00
except Exception as e:
print(f'e={e}')
2023-06-25 10:35:31 +08:00
return None
2023-06-24 17:41:17 +08:00
def ipgetter_get_external_ip():
getter = IPgetter()
ip = None
while ip is None:
2023-06-25 10:35:31 +08:00
try:
ip = getter.get_external_ip()
except:
ip = None
2023-06-24 17:41:17 +08:00
if ip:
return ip
2023-06-25 10:35:31 +08:00
time.sleep(0.1)
2023-06-24 17:41:17 +08:00
def get_external_ip():
ip = pmp_get_external_ip()
if ip:
return ip
ip = upnp_get_external_ip()
if ip:
return ip
return ipgetter_get_external_ip()
2023-06-24 18:17:18 +08:00
def outip(w):
os.dup2(w.fileno(), 1)
ip = get_external_ip()
print(ip)
def get_ip():
r, w = Pipe()
reader = os.fdopen(r.fileno(), 'r')
p = Process(None, outip, 'TESTER', (w, ))
p.start()
ip = reader.readline()
p.join()
return ip.strip()
2023-06-24 17:41:17 +08:00
def run():
while True:
2023-06-24 18:17:18 +08:00
ip = get_ip()
2023-06-24 17:41:17 +08:00
if ip:
2023-06-24 18:17:18 +08:00
print(f'{ip=}')
2023-06-24 17:41:17 +08:00
time.sleep(10)
2023-06-24 18:17:18 +08:00
if __name__ == '__main__':
run()