-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathuhdiscovery.py
More file actions
executable file
·89 lines (77 loc) · 2.73 KB
/
Copy pathuhdiscovery.py
File metadata and controls
executable file
·89 lines (77 loc) · 2.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#!/usr/bin/env python3
#
# Query local network for uHej services
#
import socket
import sys
import threading
import time
import uhej
def worker_thread():
global discovery_list
global sock
while 1:
try:
data, addr = sock.recvfrom(1024)
port = addr[1]
addr = addr[0]
frame = bytearray(data)
try:
f = uhej.decode_frame(frame)
f["source"] = addr
f["port"] = port
types = ["UDP", "TCP", "mcast"]
if uhej.ANNOUNCE == f["frame_type"]:
for s in f["services"]:
key = "%s:%s:%s" % (f["source"], s["port"], s["type"])
if key not in discovery_list:
print("%16s:%-5d %-8s %s" % (f["source"], s["port"], types[s["type"]], s["service_name"]))
discovery_list[key] = True # Keep track of which hosts we have seen
except uhej.IllegalFrameException:
pass
except socket.error as e:
print(f"Expection {e}")
def main():
global discovery_list
global sock
discovery_list = {}
ANY = "0.0.0.0"
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
try:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
except AttributeError:
pass
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 32)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, 1)
sock.bind((ANY, uhej.MCAST_PORT))
# sock.bind((MCAST_GRP, MCAST_PORT))
thread = threading.Thread(target = worker_thread)
thread.daemon = True
thread.start()
if 0:
try:
host = socket.gethostbyname(socket.gethostname()+".local")
except:
host = socket.gethostbyname(socket.gethostname())
sock.setsockopt(socket.SOL_IP, socket.IP_MULTICAST_IF, socket.inet_aton(host))
sock.setsockopt(socket.SOL_IP, socket.IP_ADD_MEMBERSHIP, socket.inet_aton(uhej.MCAST_GRP) + socket.inet_aton(ANY))
run_time_s = 10 # Run query for this many seconds
query_interval_s = 2 # Send query this often
last_query = 0
start_time = time.time()
while time.time() - start_time < run_time_s:
if time.time() - last_query > query_interval_s:
f = uhej.query(uhej.UDP, "*")
sock.sendto(f, (uhej.MCAST_GRP, uhej.MCAST_PORT))
last_query = time.time()
time.sleep(1)
num_found = len(discovery_list)
if num_found == 0:
print("No services found")
elif num_found == 1:
print("1 service found")
else:
print("%d services found" % (num_found))
sys.exit(0)
if __name__ == '__main__':
main()