How to Code an IP Pinger with Python?

Estimated read time 2 min read

To code an IP pinger with Python, you can use the ping3 library, which provides a simple way to send ICMP echo requests (pings) to remote hosts. Here’s an example of how you can implement an IP pinger using ping3:

First, install the ping3 library by running the following command:

pip install ping3

Then, use the following code to create an IP pinger:

import ping3

def ping_host(ip_address):
    response_time = ping3.ping(ip_address)
    if response_time is not None:
        print(f"Host {ip_address} is reachable (Response time: {response_time} ms)")
    else:
        print(f"Host {ip_address} is unreachable")

# Example usage
ping_host("192.168.1.1")
ping_host("google.com")

In the example above, we import the ping3 library and define a function called ping_host. The function takes an ip_address parameter and uses ping3.ping() to send an ICMP echo request to the specified IP address.

The ping3.ping() function returns the response time in milliseconds if the host is reachable, and None if the host is unreachable.

In the ping_host function, we check the response time. If it’s not None, we print a message indicating that the host is reachable along with the response time. Otherwise, we print a message indicating that the host is unreachable.

You can call the ping_host function with different IP addresses or hostnames to ping different hosts.

Note that the ability to send ICMP echo requests may require administrative privileges or special network configuration, depending on your operating system and network environment.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply