forked from pratishcs/pyicmp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.py
90 lines (83 loc) · 2.13 KB
/
handler.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
from threading import Lock
from . import ping
import time
import socket
class Handler:
identifier = 0
ports = []
l = Lock()
#this should be enough port, app will likely never use so many threads anyway
max_ports = 1024
def __init__(self, port = 33438):
self.start_port = port
def do_ping(self, ip, ttl = 64):
ip = str(ip)
#get identifier for this serie of packet
with self.l:
i = self.identifier
self.identifier += 1
#get free port to use
while True:
self.l.acquire()
if len(self.ports) >= self.max_ports:
self.l.release()
time.sleep(0.1)
else:
port = None
for port in range(self.start_port, self.start_port + self.max_ports):
if port not in self.ports:
self.ports.append(port)
break
self.l.release()
break
#now do actuall ping
p = ping.Ping(ip = ip, port = port, identifier = i, sequence = 0, ttl = 64, repeat = 2)
with self.l:
self.ports.remove(port)
return p.result
def do_trace(self, ip):
ip = str(ip)
result = []
#get identifier for this serie of packet
with self.l:
i = self.identifier
self.identifier += 1
#get free port to use
while True:
self.l.acquire()
if len(self.ports) >= self.max_ports:
self.l.release()
time.sleep(0.1)
else:
port = None
for port in range(self.start_port, self.start_port + self.max_ports):
if port not in self.ports:
self.ports.append(port)
break
self.l.release()
break
#now do actuall trace
sequence = 0
ttl = 1
on = False
while not on and ttl < 128:
p = ping.Ping(ip = ip, port = port, identifier = i, sequence = sequence, ttl = ttl, repeat = 1)
sequence += 1
ttl += 1
on = p.result['on']
try:
result.append((p.result['responses'][0][0].source_ip, socket.gethostbyaddr(p.result['responses'][0][0].source_ip)[0]))
#no PTR record
except socket.herror:
result.append((p.result['responses'][0][0].source_ip, None))
#no response from this step, ignore, useless for traceroute
except IndexError:
pass
with self.l:
self.ports.remove(port)
result = {
'ip': ip,
'reached': not ttl == 128,
'steps': result
}
return result