-
Notifications
You must be signed in to change notification settings - Fork 1
/
Subscriber.py
63 lines (49 loc) · 1.92 KB
/
Subscriber.py
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
import socket
from scapy.all import send
from scapy.layers.inet import IP, UDP
import json5
class Subscriber:
def __init__(self):
with open('./config.json5') as f:
cfg = json5.loads(f.read())
self.serv_ip = cfg['server_ip']
self.serv_port = cfg['server_port']
self.serv_addr = (self.serv_ip, self.serv_port)
self.broadcast_list = cfg['broadcast_list']
self.debug = cfg['debug']
self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
self.s.bind(self.serv_addr)
except Exception as e:
if self.debug == True:
print(f"Port {self.serv_port} has been occupied, please change port.")
if self.debug == True:
print(f"Listening Port {self.serv_port}.")
def broadcast(self, src, sport, dport, payload):
for dst in self.broadcast_list:
if dst == src[0]:
continue
if self.debug == True:
print(f'src: {(src[0], sport)}, dst: {(dst, dport)}')
try:
send(IP(src=src[0], dst=dst) / UDP(sport=sport, dport=dport) / payload)
except:
pass
def parse(self, data):
sport = int.from_bytes(data[0:2], byteorder='big')
dport = int.from_bytes(data[2:4], byteorder='big')
payload = data[4:]
return sport, dport, payload
def listen(self):
while True:
data, src = self.s.recvfrom(1024)
sport, dport, payload = self.parse(data)
if self.debug == True:
print(f'{src[0]}->{self.serv_ip}, len:{len(payload)}')
self.broadcast(src, sport, dport, payload)
def main():
s = Subscriber()
s.listen()
if __name__ == '__main__':
main()