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
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
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.