Skip to content

Instantly share code, notes, and snippets.

@c2h2
Created February 6, 2025 06:07
Show Gist options
  • Save c2h2/827805937d90aa329dc0e0388af84439 to your computer and use it in GitHub Desktop.
Save c2h2/827805937d90aa329dc0e0388af84439 to your computer and use it in GitHub Desktop.
Perform an HTTP GET request to the URL and return the latency in milliseconds.
#!/usr/bin/env python3
import requests
import time
import sys
from colorama import init, Fore, Style
# Initialize colorama for Windows and auto-reset colors
init(autoreset=True)
# URL to "ping" (using HTTP, as requested)
URL = "http://google.com"
INTERVAL = 5 # seconds
# Statistics counters
sent = 0
received = 0
latencies = []
def ping():
"""Perform an HTTP GET request to the URL and return the latency in milliseconds if successful."""
global sent, received
sent += 1
try:
start_time = time.time()
response = requests.get(URL, timeout=5)
response.raise_for_status() # Raise an exception for HTTP errors
elapsed = (time.time() - start_time) * 1000 # Convert to milliseconds
latencies.append(elapsed)
received += 1
print(f"{Fore.GREEN}Reply from {URL}: time={elapsed:.2f} ms")
except requests.RequestException as e:
print(f"{Fore.RED}Request failed: {e}")
def print_summary():
"""Print a summary similar to the ping command output."""
lost = sent - received
loss_percent = (lost / sent) * 100 if sent else 0
print("\n--- HTTP Ping statistics ---")
print(f"{sent} requests sent, {received} responses received, {loss_percent:.1f}% packet loss")
if latencies:
min_time = min(latencies)
max_time = max(latencies)
avg_time = sum(latencies) / len(latencies)
print(f"round-trip min/avg/max = {min_time:.2f}/{avg_time:.2f}/{max_time:.2f} ms")
else:
print("No successful responses to calculate round-trip times.")
def main():
print(f"Pinging {URL} every {INTERVAL} seconds. Press Ctrl+C to stop.")
try:
while True:
ping()
time.sleep(INTERVAL)
except KeyboardInterrupt:
print_summary()
sys.exit(0)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment