-
Notifications
You must be signed in to change notification settings - Fork 0
/
Socket.py
117 lines (82 loc) · 2.89 KB
/
Socket.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
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
import socket
import threading
import asyncio
from scapy.all import *
class SocketServer(threading.Thread):
def __init__(self, listen_addr, listen_port, max_conn=10, threshold=100):
threading.Thread.__init__(self)
self.listen_addr = listen_addr
self.listen_port = listen_port
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.bind((self.listen_addr, self.listen_port))
self.sock.listen(max_conn)
self.buffers = {}
self.go = threading.Event()
self.go.clear()
self.ws = None
self.event_loop = asyncio.new_event_loop()
self.THRESHOLD = threshold
def run(self):
self.go.clear()
while not self.go.is_set():
try:
conn, addr = self.sock.accept()
name = conn.recv(1024).decode()
if name in self.buffers:
print("Name %s already in use." % name)
conn.close()
continue
self.buffers[name] = []
print("Connected by", addr, name)
t = threading.Thread(target=self.handle_conn, args=(conn, addr, name))
t.start()
t2 = threading.Thread(target=self.handle_analyze, args=(name,))
t2.start()
except Exception as e:
print(e)
self.go.set()
def handle(self, data: bytes, name):
if self.ws is None:
return
try:
pkg = Ether(data)
self.buffers[name].append(pkg)
except:
return
def handle_analyze(self, name):
pass
def handle_conn(self, conn, addr, name):
while not self.go.is_set():
try:
data = conn.recv(1024)
if not data:
break
self.handle(data, name)
except (ConnectionResetError, ConnectionAbortedError):
self.go.set()
except Exception as e:
print(e)
self.go.set()
conn.close()
self.buffers.pop(name)
print("Disconnected by", addr)
def stop(self):
self.go.set()
self.sock.close()
class SocketClient:
def __init__(self, host, port, name):
self.host = host
self.port = port
self.name = name
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.connect((self.host, self.port))
self.sock.send(self.name.encode())
def send(self, data):
self.sock.send(data)
def recv(self, buffersize=1024):
return self.sock.recv(buffersize)
def disconnect(self):
self.sock.close()
def connect(self, host, port):
self.sock.connect((host, port))
self.send(self.name.encode())