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.
Related articles:
- Handling HTTP Status Codes Gracefully with Python Requests
- Keeping Sessions Active When Websites Log You Out in Python Requests
- Fixing the "Expecting Value" Error with Python Requests
- Why use Python requests?
- Controlling Redirections in Python Requests
- Inspecting Requests in Python with the Requests Library
- Making API Calls with Lists in Python Requests
Browse by tags:
Browse by language:
Popular articles:
- Web Scraping in Python - The Complete Guide
- Working with Query Parameters in Python Requests
- How to Authenticate with Bearer Tokens in Python Requests
- Building a Simple Proxy Rotator with Kotlin and Jsoup
- The Complete BeautifulSoup Cheatsheet with Examples
- The Complete Playwright Cheatsheet
- Web Scraping using ChatGPT - Complete Guide with Examples