-
Notifications
You must be signed in to change notification settings - Fork 0
/
ipv6.py
96 lines (87 loc) · 3.57 KB
/
ipv6.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
from dataclasses import dataclass
from ipaddress import IPv6Address
from util import bytes_to_int
@dataclass
class IPv6Packet:
"""
0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|Version| Traffic Class | Flow Label |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Payload Length | Next Header | Hop Limit |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
+ +
| |
+ Source Address +
| |
+ +
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
+ +
| |
+ Destination Address +
| |
+ +
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
"""
version: int
traffic_class: int
flow_label: int
payload_length: int
next_header: int # Same as ipv4 protocol field
hop_limit: int
source_address: IPv6Address
destination_address: IPv6Address
payload: bytes
def payload_length_is_in_range(self):
return 0 <= self.payload_length < 2**16
def __post_init__(self) -> None:
assert all(
(
0 <= self.version < 2**4,
0 <= self.traffic_class < 2**8,
0 <= self.flow_label < 2**20,
self.payload_length_is_in_range(),
0 <= self.next_header < 2**8,
0 <= self.hop_limit < 2**8,
)
)
def serialize(self) -> bytes:
result: bytes = b"".join(
[
bytes(
[
(self.version << 4) | (self.traffic_class >> 4),
((self.traffic_class & 0xF) << 4) | self.flow_label >> 16,
]
),
(self.flow_label & 0xFFFF).to_bytes(2),
self.payload_length.to_bytes(2),
self.next_header.to_bytes(1),
self.hop_limit.to_bytes(1),
self.source_address.packed,
self.destination_address.packed,
self.payload,
]
)
return result
@classmethod
def deserialize(cls, data: bytes):
assert len(data) >= 40
return cls(
data[0] >> 4,
((data[0] & 0xF) << 4) | (data[1] >> 4),
((data[1] & 0xF) << 16) | bytes_to_int(data[2:4]),
bytes_to_int(data[4:6]),
data[6],
data[7],
IPv6Address(data[8:24]),
IPv6Address(data[24:40]),
data[40:],
)
def fix_payload_length(self) -> None:
self.payload_length = len(self.payload)
assert self.payload_length_is_in_range()