Debian Codegraph @

icmplib/ping.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 import asyncio
30 from time import sleep
31
32 from .sockets import ICMPv4Socket, ICMPv6Socket, AsyncSocket
33 from .models import ICMPRequest, Host
34 from .exceptions import ICMPLibError
35 from .utils import *
36
37
38 def ping(address, count=4, interval=1, timeout=2, id=None, source=None,
39 family=None, privileged=True, **kwargs):
40 '''
41 Send ICMP Echo Request packets to a network host.
42
43 :type address: str
44 :param address: The IP address, hostname or FQDN of the host to
45 which messages should be sent. For deterministic behavior,
46 prefer to use an IP address.
47
48 :type count: int, optional
49 :param count: The number of ping to perform. Default to 4.
50
51 :type interval: int or float, optional
52 :param interval: The interval in seconds between sending each packet.
53 Default to 1.
54
55 :type timeout: int or float, optional
56 :param timeout: The maximum waiting time for receiving a reply in
57 seconds. Default to 2.
58
59 :type id: int, optional
60 :param id: The identifier of ICMP requests. Used to match the
61 responses with requests. In practice, a unique identifier should
62 be used for every ping process. On Linux, this identifier is
63 ignored when the `privileged` parameter is disabled. The library
64 handles this identifier itself by default.
65
66 :type source: str, optional
67 :param source: The IP address from which you want to send packets.
68 By default, the interface is automatically chosen according to
69 the specified destination.
70
71 :type family: int, optional
72 :param family: The address family if a hostname or FQDN is specified.
73 Can be set to `4` for IPv4 or `6` for IPv6 addresses. By default,
74 this function searches for IPv4 addresses first before searching
75 for IPv6 addresses.
76
77 :type privileged: bool, optional
78 :param privileged: When this option is enabled, this library fully
79 manages the exchanges and the structure of ICMP packets.
80 Disable this option if you want to use this function without
81 root privileges and let the kernel handle ICMP headers.
82 Default to True.
83 Only available on Unix systems. Ignored on Windows.
84
85 Advanced (**kwags):
86
87 :type payload: bytes, optional
88 :param payload: The payload content in bytes. A random payload is
89 used by default.
90
91 :type payload_size: int, optional
92 :param payload_size: The payload size. Ignored when the `payload`
93 parameter is set. Default to 56.
94
95 :type traffic_class: int, optional
96 :param traffic_class: The traffic class of ICMP packets.
97 Provides a defined level of service to packets by setting the DS
98 Field (formerly TOS) or the Traffic Class field of IP headers.
99 Packets are delivered with the minimum priority by default
100 (Best-effort delivery).
101 Intermediate routers must be able to support this feature.
102 Only available on Unix systems. Ignored on Windows.
103
104 :rtype: Host
105 :returns: A `Host` object containing statistics about the desired
106 destination.
107
108 :raises NameLookupError: If you pass a hostname or FQDN in
109 parameters and it does not exist or cannot be resolved.
110 :raises SocketPermissionError: If the privileges are insufficient to
111 create the socket.
112 :raises SocketAddressError: If the source address cannot be assigned
113 to the socket.
114 :raises ICMPSocketError: If another error occurs. See the
115 `ICMPv4Socket` or `ICMPv6Socket` class for details.
116
117 Usage::
118
119 >>> from icmplib import ping
120 >>> host = ping('1.1.1.1')
121 >>> host.avg_rtt
122 13.2
123 >>> host.is_alive
124 True
125
126 See the `Host` class for details.
127
128 '''
129 if is_hostname(address):
130 address = resolve(address, family)[0]
131
132 if is_ipv6_address(address):
133 _Socket = ICMPv6Socket
134 else:
135 _Socket = ICMPv4Socket
136
137 id = id or unique_identifier()
138 packets_sent = 0
139 rtts = []
140
141 with _Socket(source, privileged) as sock:
142 for sequence in range(count):
143 if sequence > 0:
144 sleep(interval)
145
146 request = ICMPRequest(
147 destination=address,
148 id=id,
149 sequence=sequence,
150 **kwargs)
151
152 try:
153 sock.send(request)
154 packets_sent += 1
155
156 reply = sock.receive(request, timeout)
157 reply.raise_for_status()
158
159 rtt = (reply.time - request.time) * 1000
160 rtts.append(rtt)
161
162 except ICMPLibError:
163 pass
164
165 return Host(address, packets_sent, rtts)
166
167
168 async def async_ping(address, count=4, interval=1, timeout=2, id=None,
169 source=None, family=None, privileged=True, **kwargs):
170 '''
171 Send ICMP Echo Request packets to a network host.
172
173 This function is non-blocking.
174
175 :type address: str
176 :param address: The IP address, hostname or FQDN of the host to
177 which messages should be sent. For deterministic behavior,
178 prefer to use an IP address.
179
180 :type count: int, optional
181 :param count: The number of ping to perform. Default to 4.
182
183 :type interval: int or float, optional
184 :param interval: The interval in seconds between sending each packet.
185 Default to 1.
186
187 :type timeout: int or float, optional
188 :param timeout: The maximum waiting time for receiving a reply in
189 seconds. Default to 2.
190
191 :type id: int, optional
192 :param id: The identifier of ICMP requests. Used to match the
193 responses with requests. In practice, a unique identifier should
194 be used for every ping process. On Linux, this identifier is
195 ignored when the `privileged` parameter is disabled. The library
196 handles this identifier itself by default.
197
198 :type source: str, optional
199 :param source: The IP address from which you want to send packets.
200 By default, the interface is automatically chosen according to
201 the specified destination.
202
203 :type family: int, optional
204 :param family: The address family if a hostname or FQDN is specified.
205 Can be set to `4` for IPv4 or `6` for IPv6 addresses. By default,
206 this function searches for IPv4 addresses first before searching
207 for IPv6 addresses.
208
209 :type privileged: bool, optional
210 :param privileged: When this option is enabled, this library fully
211 manages the exchanges and the structure of ICMP packets.
212 Disable this option if you want to use this function without
213 root privileges and let the kernel handle ICMP headers.
214 Default to True.
215 Only available on Unix systems. Ignored on Windows.
216
217 Advanced (**kwags):
218
219 :type payload: bytes, optional
220 :param payload: The payload content in bytes. A random payload is
221 used by default.
222
223 :type payload_size: int, optional
224 :param payload_size: The payload size. Ignored when the `payload`
225 parameter is set. Default to 56.
226
227 :type traffic_class: int, optional
228 :param traffic_class: The traffic class of ICMP packets.
229 Provides a defined level of service to packets by setting the DS
230 Field (formerly TOS) or the Traffic Class field of IP headers.
231 Packets are delivered with the minimum priority by default
232 (Best-effort delivery).
233 Intermediate routers must be able to support this feature.
234 Only available on Unix systems. Ignored on Windows.
235
236 :rtype: Host
237 :returns: A `Host` object containing statistics about the desired
238 destination.
239
240 :raises NameLookupError: If you pass a hostname or FQDN in
241 parameters and it does not exist or cannot be resolved.
242 :raises SocketPermissionError: If the privileges are insufficient to
243 create the socket.
244 :raises SocketAddressError: If the source address cannot be assigned
245 to the socket.
246 :raises ICMPSocketError: If another error occurs. See the
247 `ICMPv4Socket` or `ICMPv6Socket` class for details.
248
249 Usage::
250
251 >>> import asyncio
252 >>> from icmplib import async_ping
253 >>> host = asyncio.run(async_ping('1.1.1.1'))
254 >>> host.avg_rtt
255 13.2
256 >>> host.is_alive
257 True
258
259 See the `Host` class for details.
260
261 '''
262 if is_hostname(address):
263 address = (await async_resolve(address, family))[0]
264
265 if is_ipv6_address(address):
266 _Socket = ICMPv6Socket
267 else:
268 _Socket = ICMPv4Socket
269
270 id = id or unique_identifier()
271 packets_sent = 0
272 rtts = []
273
274 with AsyncSocket(_Socket(source, privileged)) as sock:
275 for sequence in range(count):
276 if sequence > 0:
277 await asyncio.sleep(interval)
278
279 request = ICMPRequest(
280 destination=address,
281 id=id,
282 sequence=sequence,
283 **kwargs)
284
285 try:
286 sock.send(request)
287 packets_sent += 1
288
289 reply = await sock.receive(request, timeout)
290 reply.raise_for_status()
291
292 rtt = (reply.time - request.time) * 1000
293 rtts.append(rtt)
294
295 except ICMPLibError:
296 pass
297
298 return Host(address, packets_sent, rtts)