Debian Codegraph @

icmplib/traceroute.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 time import sleep
30
31 from .sockets import ICMPv4Socket, ICMPv6Socket
32 from .models import ICMPRequest, Hop
33 from .exceptions import TimeExceeded, ICMPLibError
34 from .utils import *
35
36
37 def traceroute(address, count=2, interval=0.05, timeout=2, first_hop=1,
38 max_hops=30, fast=False, id=None, source=None, family=None,
39 **kwargs):
40 '''
41 Determine the route to a destination host.
42
43 The Internet is a large and complex aggregation of network hardware,
44 connected together by gateways. Tracking the route one's packets
45 follow can be difficult. This function uses the IP protocol time to
46 live field and attempts to elicit an ICMP Time Exceeded response
47 from each gateway along the path to some host.
48
49 This function requires root privileges to run.
50
51 :type address: str
52 :param address: The IP address, hostname or FQDN of the host to
53 reach. For deterministic behavior, prefer to use an IP address.
54
55 :type count: int, optional
56 :param count: The number of ping to perform per hop. Default to 2.
57
58 :type interval: int or float, optional
59 :param interval: The interval in seconds between sending each packet.
60 Default to 0.05.
61
62 :type timeout: int or float, optional
63 :param timeout: The maximum waiting time for receiving a reply in
64 seconds. Default to 2.
65
66 :type first_hop: int, optional
67 :param first_hop: The initial time to live value used in outgoing
68 probe packets. Default to 1.
69
70 :type max_hops: int, optional
71 :param max_hops: The maximum time to live (max number of hops) used
72 in outgoing probe packets. Default to 30.
73
74 :type fast: bool, optional
75 :param fast: When this option is enabled and an intermediate router
76 has been reached, skip to the next hop rather than perform
77 additional requests. The `count` parameter then becomes the
78 maximum number of requests in the event of no response.
79 Default to False.
80
81 :type id: int, optional
82 :param id: The identifier of ICMP requests. Used to match the
83 responses with requests. In practice, a unique identifier should
84 be used for every traceroute process. The library handles this
85 identifier itself by default.
86
87 :type source: str, optional
88 :param source: The IP address from which you want to send packets.
89 By default, the interface is automatically chosen according to
90 the specified destination.
91
92 :type family: int, optional
93 :param family: The address family if a hostname or FQDN is specified.
94 Can be set to `4` for IPv4 or `6` for IPv6 addresses. By default,
95 this function searches for IPv4 addresses first before searching
96 for IPv6 addresses.
97
98 Advanced (**kwags):
99
100 :type payload: bytes, optional
101 :param payload: The payload content in bytes. A random payload is
102 used by default.
103
104 :type payload_size: int, optional
105 :param payload_size: The payload size. Ignored when the `payload`
106 parameter is set. Default to 56.
107
108 :type traffic_class: int, optional
109 :param traffic_class: The traffic class of ICMP packets.
110 Provides a defined level of service to packets by setting the DS
111 Field (formerly TOS) or the Traffic Class field of IP headers.
112 Packets are delivered with the minimum priority by default
113 (Best-effort delivery).
114 Intermediate routers must be able to support this feature.
115 Only available on Unix systems. Ignored on Windows.
116
117 :rtype: list[Hop]
118 :returns: A list of `Hop` objects representing the route to the
119 desired destination. The list is sorted in ascending order
120 according to the distance, in terms of hops, that separates the
121 remote host from the current machine. Gateways that do not
122 respond to requests are not added to this list.
123
124 :raises NameLookupError: If you pass a hostname or FQDN in
125 parameters and it does not exist or cannot be resolved.
126 :raises SocketPermissionError: If the privileges are insufficient to
127 create the socket.
128 :raises SocketAddressError: If the source address cannot be assigned
129 to the socket.
130 :raises ICMPSocketError: If another error occurs. See the
131 `ICMPv4Socket` or `ICMPv6Socket` class for details.
132
133 Usage::
134
135 >>> from icmplib import traceroute
136 >>> hops = traceroute('1.1.1.1')
137 >>> last_distance = 0
138
139 >>> for hop in hops:
140 ... if last_distance + 1 != hop.distance:
141 ... print('Some gateways are not responding')
142 ...
143 ... print(f'{hop.distance} {hop.address} {hop.avg_rtt} ms')
144 ...
145 ... last_distance = hop.distance
146
147 1 10.0.0.1 5.196 ms
148 2 194.149.169.49 7.552 ms
149 3 194.149.166.54 12.21 ms
150 * Some gateways are not responding
151 5 212.73.205.22 22.15 ms
152 6 1.1.1.1 13.59 ms
153
154 See the `Hop` class for details.
155
156 '''
157 if is_hostname(address):
158 address = resolve(address, family)[0]
159
160 if is_ipv6_address(address):
161 _Socket = ICMPv6Socket
162 else:
163 _Socket = ICMPv4Socket
164
165 id = id or unique_identifier()
166 ttl = first_hop
167 host_reached = False
168 hops = []
169
170 with _Socket(source) as sock:
171 while not host_reached and ttl <= max_hops:
172 reply = None
173 packets_sent = 0
174 rtts = []
175
176 for sequence in range(count):
177 request = ICMPRequest(
178 destination=address,
179 id=id,
180 sequence=sequence,
181 ttl=ttl,
182 **kwargs)
183
184 try:
185 sock.send(request)
186 packets_sent += 1
187
188 reply = sock.receive(request, timeout)
189 rtt = (reply.time - request.time) * 1000
190 rtts.append(rtt)
191
192 reply.raise_for_status()
193 host_reached = True
194
195 except TimeExceeded:
196 sleep(interval)
197
198 except ICMPLibError:
199 break
200
201 if reply:
202 hop = Hop(
203 address=reply.source,
204 packets_sent=packets_sent,
205 rtts=rtts,
206 distance=ttl)
207
208 hops.append(hop)
209
210 ttl += 1
211
212 return hops