Package: icmplibv2
fork from -https://github.com/ValentinBELYN/icmplibFeatures:deciduous_tree:Ready-to-use:icmplib offers ready-to-use functions such as the most popular ones:ping,multipingandtraceroute.:gem:Modern:This library uses the latest technologies offered by Python 3.6+ and is fully object-oriented.:rocket:Fast:Each class and function has been designed and optimized to deliver the best performance. Some functions are also multithreaded (like themultipingfunction). You can ping the world in seconds!:nut_and_bolt:Powerful and evolutive:Easily build your own classes and functions withICMPv4andICMPv6sockets.:fire:Seamless integration of IPv6:Use IPv6 the same way you use IPv4. Automatic detection is done without impacting performance.:rainbow:Broadcast support(you must use theICMPv4Socketclass to enable it).:beer:Support of all operating systems.Tested on Linux, macOS and Windows.:metal:No dependency:icmplib is a pure Python implementation of the ICMP protocol. It does not use any external dependencies.InstallationInstall, upgrade and uninstall icmplib with these commands:$pip3installicmplib--extra-index-urlhttps://USER:PASSOWRD@pip.noia.network/icmplib--upgrade
$pip3uninstallicmplibicmplib requires Python 3.6 or later.Import icmplib into your project (only import what you need):# For simple usefromicmplibimportping,multiping,traceroute,Host,Hop# For advanced use (sockets)fromicmplibimportICMPv4Socket,ICMPv6Socket,ICMPRequest,ICMPReply# ExceptionsfromicmplibimportICMPLibError,ICMPSocketError,\SocketPermissionError,SocketBroadcastError,TimeoutExceeded,\ICMPError,DestinationUnreachable,TimeExceededBuilt-in functionsPingSendICMP ECHO_REQUESTpackets to a network host.Definitionping(address,src_addr='127.0.01',count=4,interval=1,timeout=2,id=PID)ParametersaddressThe IP address of the gateway or host to which the message should be sent.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 the request. Used to match the reply with the request.In practice, a unique identifier is used for every ping process.Type:intDefault:PIDReturn valueHostobjectAHostobject containing statistics about the desired destination:address,min_rtt,avg_rtt,max_rtt,transmitted_packets,received_packets,packet_loss,is_alive.ExceptionsSocketPermissionErrorIf the permissions are insufficient to create a socket.Example>>>host=ping('1.1.1.1',src_addr='127.0.01',count=10,interval=0.2)>>>host.address# The IP address of the gateway or host that responded'1.1.1.1'# to the request>>>host.min_rtt# The minimum round-trip time12.2>>>host.avg_rtt# The average round-trip time13.2>>>host.max_rtt# The maximum round-trip time17.6>>>host.transmitted_packets# The number of packets transmitted to the destination host10>>>host.received_packets# The number of packets sent by the remote host and received by9# the current host>>>host.packet_loss# Packet loss occurs when packets fail to reach their destination0.1# Return a float between 0 and 1 (all packets are lost)>>>host.is_alive# Return True if the host is reachable, False otherwiseTrueMultipingSendICMP ECHO_REQUESTpackets to multiple network hosts.Definitionmultiping(addresses,count=2,interval=1,timeout=2,id=PID,max_threads=10)ParametersaddressesThe IP addresses of the gateways or hosts to which messages should be sent.Type:list of strcountThe number of ping to perform per address.Type:intDefault: 2intervalThe interval in seconds between sending each packet.Type:intorfloatDefault: 1timeoutThe maximum waiting time for receiving a reply in seconds.Type:intorfloatDefault: 2idThe identifier of the requests. This identifier will be incremented by one for each destination.Type:intDefault:PIDmax_threadsThe number of threads allowed to speed up processing.Type:intDefault: 10Return valueList of HostAlist of Hostobjects containing statistics about the desired destinations:address,min_rtt,avg_rtt,max_rtt,transmitted_packets,received_packets,packet_loss,is_alive.The list is sorted in the same order as the addresses passed in parameters.ExceptionsSocketPermissionErrorIf the permissions are insufficient to create a socket.Example>>>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 alive!')......else:...print(f'{host.address}is dead!')...# 10.0.0.5 is dead!# 127.0.0.1 is alive!# ::1 is alive!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 utilizes the IP protocol time to live field and attempts to elicit anICMP TIME_EXCEEDEDresponse from each gateway along the path to some host.Definitiontraceroute(address,count=3,interval=0.05,timeout=2,id=PID,max_hops=30,fast_mode=False)ParametersaddressThe destination IP address.Type:strcountThe number of ping to perform per hop.Type:intDefault: 3intervalThe interval in seconds between sending each packet.Type:intorfloatDefault: 0.05timeoutThe maximum waiting time for receiving a reply in seconds.Type:intorfloatDefault: 2idThe identifier of the request. Used to match the reply with the request.In practice, a unique identifier is used for every ping process.Type:intDefault:PIDmax_hopsThe maximum time to live (max number of hops) used in outgoing probe packets.Type:intDefault: 30fast_modeWhen this option is enabled and an intermediate router has been reached, skip to the next hop rather than perform additional requests. Thecountoption then becomes the maximum number of requests in case of no responses.Type:boolDefault: FalseReturn valueList of HopAlist of Hopobjects representing the route to the desired host. AHopis aHostobject with an additional attribute: adistance. The list is sorted in ascending order according to the distance (in terms of hops) that separates the remote host from the current machine.ExceptionsSocketPermissionErrorIf the permissions are insufficient to create a socket.Example>>>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 routers does not respond')......# 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.19 ms# 2                 194.149.169.49          7.55 ms# 3                 194.149.166.54          12.2 ms# ***               Some routers does not respond# 5                 212.73.205.22           22.1 ms# 6                 1.1.1.1                 13.5 msICMP socketsIf you want to create your own functions and classes using the ICMP protocol, you can use theICMPv4Socket(for IPv4) and theICMPv6Socket(for IPv6 only). These classes have many methods and attributes in common. They manipulateICMPRequestandICMPReplyobjects.┌─────────────────┐
    ┌─────────────────┐   send(...)   │ ICMPSocket:     │   receive()   ┌─────────────────┐
    │   ICMPRequest   │ ────────────> │ ICMPv4Socket or │ ────────────> │    ICMPReply    │
    └─────────────────┘               │ ICMPv6Socket    │               └─────────────────┘
                                      └─────────────────┘ICMPRequestA user-created class that represents anICMP ECHO_REQUEST.DefinitionICMPRequest(destination,id,sequence,payload_size=56,timeout=2,ttl=64)Parameters / GettersdestinationThe IP address of the gateway or host to which the message should be sent.Type:stridThe identifier of the request. Used to match the reply with the request.In practice, a unique identifier is used for every ping process.Type:intsequenceThe sequence number. Used to match the reply with the request.Typically, the sequence number is incremented for each packet sent during the process.Type:intpayload_sizeThe payload size in bytes.Type:intDefault: 56timeoutThe maximum waiting time for receiving a reply in seconds.Type:intorfloatDefault: 2ttlThe time to live of the packet in seconds.Type:intDefault: 64Getters onlytimeThe timestamp of the ICMP request. Initialized to zero when creating the request and replaced byICMPv4SocketorICMPv6Socketwith the time of sending.Type:floatICMPReplyA class that represents an ICMP reply. Generated from an ICMPSocket object (ICMPv4SocketorICMPv6Socket).DefinitionICMPReply(source,id,sequence,type,code,received_bytes,time)Parameters / GetterssourceThe IP address of the gateway or host that composes the ICMP message.Type:stridThe identifier of the request. Used to match the reply with the request.Type:intsequenceThe sequence number. Used to match the reply with the request.Type:inttypeThe type of message.Type:intcodeThe error code.Type:intreceived_bytesThe number of bytes received.Type:inttimeThe timestamp of the ICMP reply.Type:floatMethodsraise_for_status()Throw an exception if the reply is not anICMP ECHO_REPLY.Otherwise, do nothing.RaisesICMPv4DestinationUnreachable: If the ICMPv4 reply is type 3.RaisesICMPv4TimeExceeded: If the ICMPv4 reply is type 11.RaisesICMPv6DestinationUnreachable: If the ICMPv6 reply is type 1.RaisesICMPv6TimeExceeded: If the ICMPv6 reply is type 3.RaisesICMPError: If the reply is of another type and is not anICMP ECHO_REPLY.ICMPv4SocketSocket for sending and receiving ICMPv4 packets.DefinitionICMPv4Socket()Methods__init__()Constructor. Automatically called: do not call it directly.RaisesSocketPermissionError: If the permissions are insufficient to create the socket.__del__()Destructor. Automatically called: do not call it directly.Call theclose()method.send(request)Send a request to a host.This operation is non-blocking. Use thereceive()method to get the reply.ParameterICMPRequest: The ICMP request you have created.RaisesSocketBroadcastError: If a broadcast address is used and the corresponding option is not enabled on the socket (ICMPv4 only).RaisesICMPSocketError: If another error occurs while sending.receive()Receive a reply from a host.This method can be called multiple times if you expect several responses (as with a broadcast address).RaisesTimeoutExceeded: If no response is received before the timeout defined in the request. This exception is also useful for stopping a possible loop in case of multiple responses.RaisesICMPSocketError: If another error occurs while receiving.ReturnsICMPReply: An ICMPReply object containing the reply of the desired destination. See the ICMPReply class for details.close()Close the socket. It cannot be used after this call.Getters / SettersbroadcastEnable or disable the broadcast support on the socket.Type:boolDefault: FalseICMPv6SocketSocket for sending and receiving ICMPv6 packets.ICMPv6Socket()MethodsThe same methods as for theICMPv4Socketclass.ExceptionsThe library contains many exceptions to adapt to your needs:ICMPLibError
 ├─ ICMPSocketError
 │  ├─ SocketPermissionError
 │  ├─ SocketBroadcastError
 │  └─ TimeoutExceeded
 │  
 └─ ICMPError
    ├─ DestinationUnreachable
    │  ├─ ICMPv4DestinationUnreachable
    │  └─ ICMPv6DestinationUnreachable
    │   
    └─ TimeExceeded
       ├─ ICMPv4TimeExceeded
       └─ ICMPv6TimeExceededICMPLibError: Exception class for the icmplib package.ICMPSocketError: Base class for ICMP sockets exceptions.SocketPermissionError: Raised when the permissions are insufficient to create a socket.SocketBroadcastError: Raised when a broadcast address is used and the corresponding option is not enabled on the socket.TimeoutExceeded: Raised when a timeout occurs on a socket.ICMPError: Base class for ICMP error messages.DestinationUnreachable: Destination Unreachable message is generated by the host or its inbound gateway to inform the client that the destination is unreachable for some reason.TimeExceeded: Time Exceeded message is generated by a gateway to inform the source of a discarded datagram due to the time to live field reaching zero. A Time Exceeded message may also be sent by a host if it fails to reassemble a fragmented datagram within its time limit.Use themessagemethod (getter) to retrieve the error message.ICMPErrorsubclasses have methods to retrieve the response (replymethod) and the specific message of the error (messagemethod).ExamplesSockets in actiondefsingle_ping(address,timeout=2,id=PID):# Create an ICMP socketsocket=ICMPv4Socket()# Create a request# See the ICMPRequest class for detailsrequest=ICMPRequest(destination=address,id=id,sequence=1,timeout=timeout)try:socket.send(request)# If the program arrives in this section,# it means that the packet has been transmittedreply=socket.receive()# If the program arrives in this section,# it means that a packet has been received# The reply has the same identifier and sequence number that# the query but it can come from an intermediate gatewayreply.raise_for_status()# If the program arrives in this section,# it means that the destination host has responded to# the requestexceptTimeoutExceededaserr:# The timeout has been reached# Equivalent to print(err.message)print(err)exceptDestinationUnreachableaserr:# The reply indicates that the destination host is# unreachableprint(err)# Retrieve the responsereply=err.replyexceptTimeExceededaserr:# The reply indicates that the time to live exceeded# in transitprint(err)# Retrieve the responsereply=err.replyexceptICMPLibErroraserr:# All other errorsprint(err)# Automatic socket closure (garbage collector)Verbose pingdefverbose_ping(address,count=4,interval=1,timeout=2,id=PID):# ICMPRequest uses a payload of 56 bytes by default# You can modify it with the payload_size parameterprint(f'PING{address}: 56 data bytes')# Automatic detection of the socket to useifis_ipv6_address(address):socket=ICMPv6Socket()else:socket=ICMPv4Socket()forsequenceinrange(count):request=ICMPRequest(destination=address,id=id,sequence=sequence,timeout=timeout)try:socket.send(request)reply=socket.receive()print(f'{reply.received_bytes}bytes from 'f'{reply.source}: ',end='')reply.raise_for_status()round_trip_time=(reply.time-request.time)*1000print(f'icmp_seq={sequence}'f'time={round(round_trip_time,2)}ms')ifsequence<count-1:sleep(interval)exceptTimeoutExceeded:print(f'Request timeout for icmp_seq{sequence}')exceptICMPErroraserr:print(err)exceptICMPLibError:print('General failure...')verbose_ping('1.1.1.1')# PING 1.1.1.1: 56 data bytes# 64 bytes from 1.1.1.1: icmp_seq=0 time=10.41 ms# 64 bytes from 1.1.1.1: icmp_seq=1 time=7.56 ms# 64 bytes from 1.1.1.1: icmp_seq=2 time=11.81 ms# 64 bytes from 1.1.1.1: icmp_seq=3 time=10.75 msFAQHow to resolve a FQDN / domain name?Python has a method to do this in its libraries:>>>importsocket>>>socket.gethostbyname('github.com')'140.82.118.4'ContributingComments 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.:beer: Donate via PayPalLicenseCopyright 2017-2019 Valentin BELYN.Code released under the GNU LGPLv3 license. See theLICENSEfor details.