-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlayer3.py
49 lines (45 loc) · 1.6 KB
/
layer3.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
#!/usr/bin/python3
from constants import L3_DATA, L3_CONFIRMATION
from layer4 import Layer4
from utils import Utils
class Layer3:
def __init__(self, data=b'', source=b'', destination=b'', packet=0, ttl=15, packet_type=L3_DATA, confirmation=0):
self.version = 1
self.packet_number = packet
self.type = packet_type
self.ttl = ttl
self.confirmation_id = confirmation
self.source = source
self.destination = destination
self.payload = data
def __bytes__(self):
return (
(chr(self.version) +
Utils.int_to_bytestring(self.packet_number, 2) +
chr(self.type) +
chr(self.ttl) +
Utils.int_to_bytestring(self.confirmation_id, 2) +
chr(0)).encode() +
self.source +
self.destination +
self.payload.__bytes__())
# use the md5 hash as a integer?
@staticmethod
def parse_l3(packet):
if packet[3] == L3_DATA:
return Layer3(
packet_type=L3_DATA,
source=packet[8:24],
destination=packet[24:40],
ttl=packet[4],
packet=int.from_bytes(packet[1:3], byteorder='big'),
data=Layer4.parse_l4(packet[40:]),
)
elif packet[3] == L3_CONFIRMATION:
return Layer3(
packet_type=L3_CONFIRMATION,
source=packet[8:24],
destination=packet[24:40],
ttl=packet[4],
confirmation=int.from_bytes(packet[5:7], byteorder='big')
)