ping3

5.1.5 · active · verified Sun Apr 12

ping3 is a pure Python3 library for implementing ICMP ping using raw sockets. It provides a straightforward API to send ICMP echo requests and receive replies, with support for both IPv4 and IPv6, and robust error handling. The library is actively maintained with a regular release cadence, ensuring ongoing compatibility and feature enhancements.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates basic ICMP ping functionality using `ping3.ping()`. It includes best practices for robust error handling by enabling `ping3.EXCEPTIONS = True` and catching various `ping3.errors` subclasses. It also highlights common `OSError`s related to raw socket permissions.

import ping3
import os

# By default, ping() returns False on HostUnknown and None on Timeout.
# For more detailed error handling, set ping3.EXCEPTIONS = True.
ping3.EXCEPTIONS = True

try:
    # Ping a well-known host
    delay = ping3.ping("example.com", timeout=2)
    if delay is not None: # delay can be 0.0 (fast) or actual time
        print(f"Ping to example.com: {delay:.2f} seconds")
    else:
        print("Ping to example.com failed (no reply).")

    # Example of an unknown host (will raise HostUnknown with EXCEPTIONS=True)
    # ping3.ping("not.exist.com")

    # Example with a very short TTL (might raise TimeToLiveExpired)
    # ping3.ping("example.com", ttl=1)

except ping3.errors.Timeout:
    print("Ping timed out.")
except ping3.errors.HostUnknown:
    print("Host unknown or could not be resolved.")
except ping3.errors.TimeToEndLiveExpired as e: # Catch specific error with new attributes
    print(f"Time to live expired. Source: {e.ip_header.get('src_addr', 'N/A')}")
except ping3.errors.PingError as e: # Catch all other ping3-specific errors
    print(f"An ICMP ping error occurred: {e}")
except OSError as e:
    # This often indicates permission issues for raw sockets on non-Linux systems or without capabilities.
    print(f"OS error during ping: {e}. You might need root privileges or specific capabilities.")
    print("On Linux, try: sudo setcap cap_net_raw+ep $(eval readlink -f $(which python))")

view raw JSON →