icmplib
icmplib (current version 3.0.4) is a pure Python library designed for easily forging ICMP packets and building network tools like ping and traceroute without relying on external dependencies. It is actively developed, offering both synchronous and asynchronous APIs, and provides cross-platform compatibility for Linux, macOS, and Windows, supporting both IPv4 and IPv6. It requires Python 3.7 or later.
Warnings
- breaking Version 3.0.0 introduced a significant breaking change by making the library primarily asynchronous. All core functions like `ping`, `multiping`, and `traceroute` were rewritten to be non-blocking.
- gotcha When using `icmplib` on Unix-like systems (Linux, macOS), creating raw ICMP sockets often requires root privileges, which can raise a `SocketPermissionError`.
- breaking Version 2.0.0 introduced a 'new library architecture' and changed how the library handles root privileges, adding the ability to use it without root privileges by setting the `privileged` parameter.
- gotcha As of version 3.0.2, the `payload` property of an `ICMPRequest` object now returns a random value if the payload is not explicitly defined, instead of `None`.
Install
-
pip install icmplib
Imports
- async_ping
from icmplib import async_ping
- Host
from icmplib import Host
- SocketPermissionError
from icmplib import SocketPermissionError
Quickstart
import asyncio
from icmplib import async_ping
async def check_host(address):
try:
host = await async_ping(address, count=4, interval=0.2, timeout=2)
if host.is_alive:
print(f"{host.address} is UP! Latency: {host.avg_rtt:.2f} ms")
else:
print(f"{host.address} is DOWN.")
except Exception as e:
print(f"Error checking {address}: {e}")
if __name__ == "__main__":
target_address = "example.com" # Replace with an IP address or hostname
asyncio.run(check_host(target_address))