Debian Codegraph @

icmplib/models.py

raw
1 '''
2 icmplib
3 ~~~~~~~
4
5 Easily forge ICMP packets and make your own ping and traceroute.
6
7 https://github.com/ValentinBELYN/icmplib
8
9 :copyright: Copyright 2017-2023 Valentin BELYN.
10 :license: GNU LGPLv3, see the LICENSE for details.
11
12 ~~~~~~~
13
14 This program is free software: you can redistribute it and/or
15 modify it under the terms of the GNU Lesser General Public License
16 as published by the Free Software Foundation, either version 3 of
17 the License, or (at your option) any later version.
18
19 This program is distributed in the hope that it will be useful,
20 but WITHOUT ANY WARRANTY; without even the implied warranty of
21 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 GNU Lesser General Public License for more details.
23
24 You should have received a copy of the GNU Lesser General Public
25 License along with this program. If not, see
26 <https://www.gnu.org/licenses/>.
27 '''
28
29 from .exceptions import *
30 from .utils import random_byte_message
31
32
33 class ICMPRequest:
34 '''
35 A user-created object that represents an ICMP Echo Request.
36
37 :type destination: str
38 :param destination: The IP address of the host to which the message
39 should be sent.
40
41 :type id: int
42 :param id: The identifier of the request. Used to match the reply
43 with the request. In practice, a unique identifier is used for
44 every ping process. On Linux, this identifier is automatically
45 replaced if the request is sent from an unprivileged socket.
46
47 :type sequence: int
48 :param sequence: The sequence number. Used to match the reply with
49 the request. Typically, the sequence number is incremented for
50 each packet sent during the process.
51
52 :type payload: bytes, optional
53 :param payload: The payload content in bytes. A random payload is
54 used by default.
55
56 :type payload_size: int, optional
57 :param payload_size: The payload size. Ignored when the `payload`
58 parameter is set. Default to 56.
59
60 :type ttl: int, optional
61 :param ttl: The time to live of the packet in terms of hops.
62 Default to 64.
63
64 :type traffic_class: int, optional
65 :param traffic_class: The traffic class of the ICMP packet.
66 Provides a defined level of service to the packet by setting the
67 DS Field (formerly TOS) or the Traffic Class field of the IP
68 header. Packets are delivered with the minimum priority by
69 default (Best-effort delivery).
70 Intermediate routers must be able to support this feature.
71 Only available on Unix systems. Ignored on Windows.
72
73 '''
74 __slots__ = '_destination', '_id', '_sequence', '_payload', \
75 '_payload_size', '_ttl', '_traffic_class', '_time'
76
77 def __init__(self, destination, id, sequence, payload=None,
78 payload_size=56, ttl=64, traffic_class=0):
79
80 if payload:
81 payload_size = len(payload)
82
83 self._destination = destination
84 self._id = id & 0xffff
85 self._sequence = sequence & 0xffff
86 self._payload = payload
87 self._payload_size = payload_size
88 self._ttl = ttl
89 self._traffic_class = traffic_class
90 self._time = 0
91
92 def __repr__(self):
93 return f'<ICMPRequest [{self._destination}]>'
94
95 @property
96 def destination(self):
97 '''
98 The IP address of the host to which the message should be sent.
99
100 '''
101 return self._destination
102
103 @property
104 def id(self):
105 '''
106 The identifier of the request.
107 Used to match the reply with the request.
108
109 '''
110 return self._id
111
112 @property
113 def sequence(self):
114 '''
115 The sequence number.
116 Used to match the reply with the request.
117
118 '''
119 return self._sequence
120
121 @property
122 def payload(self):
123 '''
124 The payload content in bytes.
125 Return a random payload if not defined.
126
127 '''
128 return self._payload or random_byte_message(self._payload_size)
129
130 @property
131 def payload_size(self):
132 '''
133 The payload size.
134
135 '''
136 return self._payload_size
137
138 @property
139 def ttl(self):
140 '''
141 The time to live of the packet in terms of hops.
142
143 '''
144 return self._ttl
145
146 @property
147 def traffic_class(self):
148 '''
149 The traffic class of the packet.
150
151 '''
152 return self._traffic_class
153
154 @property
155 def time(self):
156 '''
157 The timestamp of the ICMP request.
158
159 Initialized to zero when creating the request and replaced by
160 the `send` method of an ICMP socket with the time of sending.
161
162 '''
163 return self._time
164
165
166 class ICMPReply:
167 '''
168 A class that represents an ICMP reply. Generated from an ICMP socket.
169
170 :type source: str
171 :param source: The IP address of the host that composes the ICMP
172 message.
173
174 :type family: int
175 :param family: The address family. Can be set to `4` for IPv4 or `6`
176 for IPv6 addresses.
177
178 :type id: int
179 :param id: The identifier of the reply. Used to match the reply with
180 the request.
181
182 :type sequence: int
183 :param sequence: The sequence number. Used to match the reply with
184 the request.
185
186 :type type: int
187 :param type: The type of ICMP message.
188
189 :type code: int
190 :param code: The ICMP error code.
191
192 :type bytes_received: int
193 :param bytes_received: The number of bytes received.
194
195 :type time: float
196 :param time: The timestamp of the ICMP reply.
197
198 '''
199 __slots__ = '_source', '_family', '_id', '_sequence', '_type', \
200 '_code', '_bytes_received', '_time'
201
202 def __init__(self, source, family, id, sequence, type, code,
203 bytes_received, time):
204
205 self._source = source
206 self._family = family
207 self._id = id
208 self._sequence = sequence
209 self._type = type
210 self._code = code
211 self._bytes_received = bytes_received
212 self._time = time
213
214 def __repr__(self):
215 return f'<ICMPReply [{self._source}]>'
216
217 def raise_for_status(self):
218 '''
219 Throw an exception if the reply is not an ICMP Echo Reply.
220 Otherwise, do nothing.
221
222 :raises DestinationUnreachable: If the destination is
223 unreachable for some reason.
224 :raises TimeExceeded: If the time to live field of the ICMP
225 request has reached zero.
226 :raises ICMPError: Raised for any other type and ICMP error
227 code, except ICMP Echo Reply messages.
228
229 '''
230 if self._family == 6:
231 if self._type == 1:
232 raise ICMPv6DestinationUnreachable(self)
233
234 if self._type == 3:
235 raise ICMPv6TimeExceeded(self)
236 else:
237 if self._type == 3:
238 raise ICMPv4DestinationUnreachable(self)
239
240 if self._type == 11:
241 raise ICMPv4TimeExceeded(self)
242
243 if (self._family == 4 and self._type != 0 or
244 self._family == 6 and self._type != 129):
245 message = f'Error type: {self._type}, code: {self._code}'
246 raise ICMPError(message, self)
247
248 @property
249 def source(self):
250 '''
251 The IP address of the host that composes the ICMP message.
252
253 '''
254 return self._source
255
256 @property
257 def id(self):
258 '''
259 The identifier of the reply.
260 Used to match the reply with the request.
261
262 '''
263 return self._id
264
265 @property
266 def sequence(self):
267 '''
268 The sequence number.
269 Used to match the reply with the request.
270
271 '''
272 return self._sequence
273
274 @property
275 def type(self):
276 '''
277 The type of ICMP message.
278
279 '''
280 return self._type
281
282 @property
283 def code(self):
284 '''
285 The ICMP error code.
286
287 '''
288 return self._code
289
290 @property
291 def bytes_received(self):
292 '''
293 The number of bytes received.
294
295 '''
296 return self._bytes_received
297
298 @property
299 def time(self):
300 '''
301 The timestamp of the ICMP reply.
302
303 '''
304 return self._time
305
306
307 class Host:
308 '''
309 A class that represents a host. It simplifies the use of the results
310 from the `ping`, `multiping` and `traceroute` functions.
311
312 :type address: str
313 :param address: The IP address of the host that responded to the
314 request.
315
316 :type packets_sent: int
317 :param packets_sent: The number of packets transmitted to the
318 destination host.
319
320 :type rtts: list[float]
321 :param rtts: The list of round-trip times expressed in milliseconds.
322
323 '''
324 __slots__ = '_address', '_packets_sent', '_rtts'
325
326 def __init__(self, address, packets_sent, rtts):
327 self._address = address
328 self._packets_sent = packets_sent
329 self._rtts = rtts
330
331 def __repr__(self):
332 return f'<Host [{self._address}]>'
333
334 def __str__(self):
335 return f' {self._address}\n' + '-' * 60 + '\n' \
336 f' Packets sent: {self._packets_sent}\n' \
337 f' Packets received: {self.packets_received}\n' \
338 f' Packet loss: {self.packet_loss * 100}%\n' \
339 f' Round-trip times: {self.min_rtt} ms / ' \
340 f'{self.avg_rtt} ms / {self.max_rtt} ms\n' \
341 f' Jitter: {self.jitter} ms\n' + '-' * 60
342
343 @property
344 def address(self):
345 '''
346 The IP address of the host that responded to the request.
347
348 '''
349 return self._address
350
351 @property
352 def min_rtt(self):
353 '''
354 The minimum round-trip time in milliseconds.
355
356 '''
357 if not self._rtts:
358 return 0.0
359
360 return round(min(self._rtts), 3)
361
362 @property
363 def avg_rtt(self):
364 '''
365 The average round-trip time in milliseconds.
366
367 '''
368 if not self._rtts:
369 return 0.0
370
371 return round(sum(self._rtts) / len(self._rtts), 3)
372
373 @property
374 def max_rtt(self):
375 '''
376 The maximum round-trip time in milliseconds.
377
378 '''
379 if not self._rtts:
380 return 0.0
381
382 return round(max(self._rtts), 3)
383
384 @property
385 def rtts(self):
386 '''
387 The list of round-trip times expressed in milliseconds.
388
389 '''
390 return self._rtts
391
392 @property
393 def packets_sent(self):
394 '''
395 The number of requests transmitted to the remote host.
396
397 '''
398 return self._packets_sent
399
400 @property
401 def packets_received(self):
402 '''
403 The number of ICMP responses received from the remote host.
404
405 '''
406 return len(self._rtts)
407
408 @property
409 def packet_loss(self):
410 '''
411 Packet loss occurs when packets fail to reach their destination.
412 Return a `float` between 0 and 1 (all packets are lost).
413
414 '''
415 if not self._packets_sent:
416 return 0.0
417
418 return round(1 - len(self._rtts) / self._packets_sent, 2)
419
420 @property
421 def jitter(self):
422 '''
423 The jitter in milliseconds, defined as the variance of the
424 latency of packets flowing through the network.
425
426 At least two ICMP responses are required to calculate the
427 jitter.
428
429 '''
430 sum_deltas = 0.0
431 num_deltas = len(self._rtts) - 1
432
433 if num_deltas < 1:
434 return 0.0
435
436 for i in range(num_deltas):
437 sum_deltas += abs(self._rtts[i] - self._rtts[i + 1])
438
439 return round(sum_deltas / num_deltas, 3)
440
441 @property
442 def is_alive(self):
443 '''
444 Indicate whether the host is reachable.
445 Return a `boolean`.
446
447 '''
448 return len(self._rtts) > 0
449
450
451 class Hop(Host):
452 '''
453 A class that represents a hop. It extends the `Host` class and adds
454 some features for the `traceroute` function.
455
456 :type address: str
457 :param address: The IP address of the gateway or host that responded
458 to the request.
459
460 :type packets_sent: int
461 :param packets_sent: The number of packets transmitted to the
462 destination host.
463
464 :type rtts: list[float]
465 :param rtts: The list of round-trip times expressed in milliseconds.
466
467 :type distance: int
468 :param distance: The distance, in terms of hops, that separates the
469 remote host from the current machine.
470
471 '''
472 __slots__ = '_address', '_packets_sent', '_rtts', '_distance'
473
474 def __init__(self, address, packets_sent, rtts, distance):
475 super().__init__(address, packets_sent, rtts)
476 self._distance = distance
477
478 def __repr__(self):
479 return f'<Hop {self._distance} [{self._address}]>'
480
481 def __str__(self):
482 return f' #{self._distance:<2} {super().__str__()[2:]}'
483
484 @property
485 def distance(self):
486 '''
487 The distance, in terms of hops, that separates the remote host
488 from the current machine.
489
490 '''
491 return self._distance