Package: icmplib
icmplib is a brand new and modern implementation of the ICMP protocol in Python.Use the built-in functions or build your own, you have the choice!Features🌳Ready-to-use:icmplib offers ready-to-use functions such as the most popular ones:ping,multipingandtraceroute. An extensive documentation also helps you get started.💎Modern:This library uses the latest mechanisms offered by Python 3.7+ and is fully object-oriented.🚀Fast:Each class and function has been designed and optimized to deliver the best performance. Some functions are also asynchronous like theasync_pingandasync_multipingfunctions. You can ping the world in seconds!⚡️Powerful:Use the library without root privileges, set the traffic class of ICMP packets, customize their payload, send broadcast requests and more!🔩Evolutive:Easily build your own classes and functions withICMPv4andICMPv6sockets.🔥Seamless integration of IPv6:Use IPv6 the same way you use IPv4.🍺Cross-platform:Optimized for Linux, macOS and Windows. The library automatically manages the specificities of each system.🤘No dependency:icmplib is a pure Python implementation of the ICMP protocol. It does not rely on any external dependency.InstallationInstall icmplibThe recommended way to install icmplib is to usepip3:$pip3installicmplibImport basic functionsfromicmplibimportping,multiping,traceroute,resolveImport asynchronous functionsfromicmplibimportasync_ping,async_multiping,async_resolveImport sockets (advanced)fromicmplibimportICMPv4Socket,ICMPv6Socket,AsyncSocket,ICMPRequest,ICMPReplyImport exceptionsfromicmplibimportICMPLibError,NameLookupError,ICMPSocketErrorfromicmplibimportSocketAddressError,SocketPermissionErrorfromicmplibimportSocketUnavailableError,SocketBroadcastError,TimeoutExceededfromicmplibimportICMPError,DestinationUnreachable,TimeExceededImport only what you need.Getting startedpingSend ICMP Echo Request packets to a network host.ping(address,count=4,interval=1,timeout=2,id=None,source=None,family=None,privileged=True,**kwargs)ParametersaddressThe IP address, hostname or FQDN of the host to which messages should be sent. For deterministic behavior, prefer to use an IP address.Type:strcountThe number of ping to perform.Type:intDefault:4intervalThe interval in seconds between sending each packet.Type:intorfloatDefault:1timeoutThe maximum waiting time for receiving a reply in seconds.Type:intorfloatDefault:2idThe identifier of ICMP requests. Used to match the responses with requests. In practice, a unique identifier should be used for every ping process. On Linux, this identifier is ignored when theprivilegedparameter is disabled. The library handles this identifier itself by default.Type:intDefault:NonesourceThe IP address from which you want to send packets. By default, the interface is automatically chosen according to the specified destination.Type:strDefault:NonefamilyThe address family if a hostname or FQDN is specified. Can be set to4for IPv4 or6for IPv6 addresses. By default, this function searches for IPv4 addresses first before searching for IPv6 addresses.Type:intDefault:NoneprivilegedWhen this option is enabled, this library fully manages the exchanges and the structure of ICMP packets. Disable this option if you want to use this function without root privileges and let the kernel handle ICMP headers.Learn more about theprivilegedparameter.Only available on Unix systems. Ignored on Windows.Type:boolDefault:TruepayloadThe payload content in bytes. A random payload is used by default.Type:bytesDefault:Nonepayload_sizeThe payload size. Ignored when thepayloadparameter is set.Type:intDefault:56traffic_classThe traffic class of ICMP packets. Provides a defined level of service to packets by setting the DS Field (formerly TOS) or the Traffic Class field of IP headers. Packets are delivered with the minimum priority by default (Best-effort delivery). Intermediate routers must be able to support this feature.Only available on Unix systems. Ignored on Windows.Type:intDefault:0Return valueAHostobject containing statistics about the desired destination:address,min_rtt,avg_rtt,max_rtt,rtts,packets_sent,packets_received,packet_loss,jitter,is_aliveExceptionsNameLookupErrorIf you pass a hostname or FQDN in parameters and it does not exist or cannot be resolved.SocketPermissionErrorIf the privileges are insufficient to create the socket.SocketAddressErrorIf the source address cannot be assigned to the socket.ICMPSocketErrorIf another error occurs. See theICMPv4SocketorICMPv6Socketclass for details.Example>>>fromicmplibimportping>>>host=ping('1.1.1.1',count=10,interval=0.2)>>>host.address# The IP address of the host that responded'1.1.1.1'# to the request>>>host.min_rtt# The minimum round-trip time in milliseconds5.761>>>host.avg_rtt# The average round-trip time in milliseconds12.036>>>host.max_rtt# The maximum round-trip time in milliseconds16.207>>>host.rtts# The list of round-trip times expressed in[11.595,13.135,9.614,# milliseconds16.018,11.960,5.761,# The results are not rounded unlike other16.207,11.937,12.098]# properties>>>host.packets_sent# The number of requests transmitted to the10# remote host>>>host.packets_received# The number of ICMP responses received from9# the remote host>>>host.packet_loss# Packet loss occurs when packets fail to0.1# reach their destination. Returns a float# between 0 and 1 (all packets are lost)>>>host.jitter# The jitter in milliseconds, defined as the4.575# variance of the latency of packets flowing# through the network>>>host.is_alive# Indicates whether the host is reachableTruemultipingSend ICMP Echo Request packets to several network hosts.multiping(addresses,count=2,interval=0.5,timeout=2,concurrent_tasks=50,source=None,family=None,privileged=True,**kwargs)ParametersaddressesThe IP addresses of the hosts to which messages should be sent. Hostnames and FQDNs are allowed but not recommended. You can easily retrieve their IP address by calling the built-inresolvefunction.Type:list[str]countThe number of ping to perform per address.Type:intDefault:2intervalThe interval in seconds between sending each packet.Type:intorfloatDefault:0.5timeoutThe maximum waiting time for receiving a reply in seconds.Type:intorfloatDefault:2concurrent_tasksThe maximum number of concurrent tasks to speed up processing. This value cannot exceed the maximum number of file descriptors configured on the operating system.Type:intDefault:50sourceThe IP address from which you want to send packets. By default, the interface is automatically chosen according to the specified destinations. This parameter should not be used if you are passing both IPv4 and IPv6 addresses to this function.Type:strDefault:NonefamilyThe address family if a hostname or FQDN is specified. Can be set to4for IPv4 or6for IPv6 addresses. By default, this function searches for IPv4 addresses first before searching for IPv6 addresses.Type:intDefault:NoneprivilegedWhen this option is enabled, this library fully manages the exchanges and the structure of ICMP packets. Disable this option if you want to use this function without root privileges and let the kernel handle ICMP headers.Learn more about theprivilegedparameter.Only available on Unix systems. Ignored on Windows.Type:boolDefault:TruepayloadThe payload content in bytes. A random payload is used by default.Type:bytesDefault:Nonepayload_sizeThe payload size. Ignored when thepayloadparameter is set.Type:intDefault:56traffic_classThe traffic class of ICMP packets. Provides a defined level of service to packets by setting the DS Field (formerly TOS) or the Traffic Class field of IP headers. Packets are delivered with the minimum priority by default (Best-effort delivery). Intermediate routers must be able to support this feature.Only available on Unix systems. Ignored on Windows.Type:intDefault:0Return valueA list ofHostobjects containing statistics about the desired destinations:address,min_rtt,avg_rtt,max_rtt,rtts,packets_sent,packets_received,packet_loss,jitter,is_aliveThe list is sorted in the same order as the addresses passed in parameters.ExceptionsNameLookupErrorIf you pass a hostname or FQDN in parameters and it does not exist or cannot be resolved.SocketPermissionErrorIf the privileges are insufficient to create the socket.SocketAddressErrorIf the source address cannot be assigned to the socket.ICMPSocketErrorIf another error occurs. See theICMPv4SocketorICMPv6Socketclass for details.Example>>>fromicmplibimportmultiping>>>hosts=multiping(['10.0.0.5','127.0.0.1','::1'])>>>forhostinhosts:...ifhost.is_alive:...# See the Host class for details...print(f'{host.address}is up!')...else:...print(f'{host.address}is down!')# 10.0.0.5 is down!# 127.0.0.1 is up!# ::1 is up!tracerouteDetermine the route to a destination host.The Internet is a large and complex aggregation of network hardware, connected together by gateways. Tracking the route one's packets follow can be difficult. This function uses the IP protocol time to live field and attempts to elicit an ICMP Time Exceeded response from each gateway along the path to some host.This function requires root privileges to run.traceroute(address,count=2,interval=0.05,timeout=2,first_hop=1,max_hops=30,fast=False,id=None,source=None,family=None,**kwargs)ParametersaddressThe IP address, hostname or FQDN of the host to reach. For deterministic behavior, prefer to use an IP address.Type:strcountThe number of ping to perform per hop.Type:intDefault:2intervalThe interval in seconds between sending each packet.Type:intorfloatDefault:0.05timeoutThe maximum waiting time for receiving a reply in seconds.Type:intorfloatDefault:2first_hopThe initial time to live value used in outgoing probe packets.Type:intDefault:1max_hopsThe maximum time to live (max number of hops) used in outgoing probe packets.Type:intDefault:30fastWhen this option is enabled and an intermediate router has been reached, skip to the next hop rather than perform additional requests. Thecountparameter then becomes the maximum number of requests in the event of no response.Type:boolDefault:FalseidThe identifier of ICMP requests. Used to match the responses with requests. In practice, a unique identifier should be used for every traceroute process. The library handles this identifier itself by default.Type:intDefault:NonesourceThe IP address from which you want to send packets. By default, the interface is automatically chosen according to the specified destination.Type:strDefault:NonefamilyThe address family if a hostname or FQDN is specified. Can be set to4for IPv4 or6for IPv6 addresses. By default, this function searches for IPv4 addresses first before searching for IPv6 addresses.Type:intDefault:NonepayloadThe payload content in bytes. A random payload is used by default.Type:bytesDefault:Nonepayload_sizeThe payload size. Ignored when thepayloadparameter is set.Type:intDefault:56traffic_classThe traffic class of ICMP packets. Provides a defined level of service to packets by setting the DS Field (formerly TOS) or the Traffic Class field of IP headers. Packets are delivered with the minimum priority by default (Best-effort delivery). Intermediate routers must be able to support this feature.Only available on Unix systems. Ignored on Windows.Type:intDefault:0Return valueA list ofHopobjects representing the route to the desired destination. AHophas the same properties as aHostobject but it also has adistance:address,min_rtt,avg_rtt,max_rtt,rtts,packets_sent,packets_received,packet_loss,jitter,is_alive,distanceThe list is sorted in ascending order according to the distance, in terms of hops, that separates the remote host from the current machine. Gateways that do not respond to requests are not added to this list.ExceptionsNameLookupErrorIf you pass a hostname or FQDN in parameters and it does not exist or cannot be resolved.SocketPermissionErrorIf the privileges are insufficient to create the socket.SocketAddressErrorIf the source address cannot be assigned to the socket.ICMPSocketErrorIf another error occurs. See theICMPv4SocketorICMPv6Socketclass for details.Example>>>fromicmplibimporttraceroute>>>hops=traceroute('1.1.1.1')>>>print('Distance/TTL    Address    Average round-trip time')>>>last_distance=0>>>forhopinhops:...iflast_distance+1!=hop.distance:...print('Some gateways are not responding')......# See the Hop class for details...print(f'{hop.distance}{hop.address}{hop.avg_rtt}ms')......last_distance=hop.distance# Distance/TTL    Address                 Average round-trip time# 1               10.0.0.1                5.196 ms# 2               194.149.169.49          7.552 ms# 3               194.149.166.54          12.21 ms# *               Some gateways are not responding# 5               212.73.205.22           22.15 ms# 6               1.1.1.1                 13.59 msasync_pingSend ICMP Echo Request packets to a network host.This function is non-blocking.async_ping(address,count=4,interval=1,timeout=2,id=None,source=None,family=None,privileged=True,**kwargs)Parameters, return value and exceptionsThe same parameters, return value and exceptions as for thepingfunction.Example>>>importasyncio>>>fromicmplibimportasync_ping>>>asyncdefis_alive(address):...host=awaitasync_ping(address,count=10,interval=0.2)...returnhost.is_alive>>>asyncio.run(is_alive('1.1.1.1'))Trueasync_multipingSend ICMP Echo Request packets to several network hosts.This function is non-blocking.async_multiping(addresses,count=2,interval=0.5,timeout=2,concurrent_tasks=50,source=None,family=None,privileged=True,**kwargs)Parameters, return value and exceptionsThe same parameters, return values and exceptions as for themultipingfunction.Example>>>importasyncio>>>fromicmplibimportasync_multiping>>>asyncdefare_alive(*addresses):...hosts=awaitasync_multiping(addresses)......forhostinhosts:...ifnothost.is_alive:...returnFalse......returnTrue>>>asyncio.run(are_alive('10.0.0.5','127.0.0.1','::1'))FalseDocumentationThis page only gives an overview of the features of icmplib.To learn more about the built-in functions, on how to create your own and handle exceptions, you can click on the following link:🚀DocumentationContributingComments and enhancements are welcome.All development is done onGitHub. UseIssuesto report problems and submit feature requests. Please include a minimal example that reproduces the bug.Donateicmplib is completely free and open source. It has been fully developed on my free time. If you enjoy it, please consider donating to support the development.🎉Donate via PayPalLicenseCopyright 2017-2023 Valentin BELYN.Code released under the GNU LGPLv3 license. See theLICENSEfor details.