Files
IKAR/tool/discover_gateway.py
T

15 lines
835 B
Python

import json,socket,time,urllib.request,xml.etree.ElementTree as ET
s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM,socket.IPPROTO_UDP)
s.settimeout(1)
request='M-SEARCH * HTTP/1.1\r\nHOST: 239.255.255.250:1900\r\nMAN: "ssdp:discover"\r\nMX: 2\r\nST: urn:schemas-upnp-org:device:InternetGatewayDevice:1\r\n\r\n'
s.sendto(request.encode(),('239.255.255.250',1900))
locations=set(); end=time.monotonic()+4
while time.monotonic()<end:
try:
data,address=s.recvfrom(8192)
headers=dict(line.split(':',1) for line in data.decode(errors='replace').splitlines()[1:] if ':' in line)
location=next((value.strip() for key,value in headers.items() if key.lower()=='location'),None)
if location: locations.add(location)
except socket.timeout: pass
print(json.dumps({'gatewayDescriptions':sorted(locations)}))