Using Python Requests to Ping an IP Address

Feb 3, 2024 ยท 2 min read

The Python Requests library provides a simple way to ping an IP address and check if it is reachable. In this guide, we'll cover how to ping an IP address with Requests and handle errors gracefully.

Ping an IP Address

We can use the get() method in Requests to ping an IP address. Here is an example:

import requests

ip = "8.8.8.8" 

try:
    response = requests.get("http://" + ip, timeout=5)
    print(f"{ip} is reachable")
except requests.ConnectionError:
    print(f"Failed to reach {ip}")

We build the URL using the IP address and use requests.get() to make the request. The timeout parameter sets the time to wait for a response in seconds before raising a connection error.

Inside the try/except block, we print a message if the request succeeded or failed. This handles errors gracefully.

Ping Multiple IPs

To check multiple IPs, we can loop through a list of IPs:

ips = ["8.8.8.8", "1.1.1.1", "192.168.0.1"]

for ip in ips:
    try: 
        response = requests.get(f"http://{ip}", timeout=1)
        print(f"{ip} is reachable")
    except requests.ConnectionError:
        print(f"Failed to reach {ip}")

This pings each IP in sequence and prints the result. Adjust the timeout as needed.

The Requests library provides an easy way to ping IPs and check connectivity from Python scripts. With error handling, we can ping devices and get clean results.

Browse by tags:

Browse by language:

Tired of getting blocked while scraping the web?

ProxiesAPI handles headless browsers and rotates proxies for you.
Get access to 1,000 free API credits, no credit card required!