Skip to content

Instantly share code, notes, and snippets.

@hadifarnoud
Last active May 30, 2024 18:29
Show Gist options
  • Save hadifarnoud/7e35ace3f231cdb36623bbc358f4888b to your computer and use it in GitHub Desktop.
Save hadifarnoud/7e35ace3f231cdb36623bbc358f4888b to your computer and use it in GitHub Desktop.
#!/bin/bash
# URL to check for internet connectivity
URL="https://cp.cloudflare.com/generate_204"
INTERVAL=60 # Interval in seconds between checks
RETRIES=3 # Number of retries before concluding that the internet is down
RETRY_DELAY=1 # Delay in seconds between retries
CURL_TIMEOUT=1 # Curl timeout in seconds
# Function to check connectivity and measure latency
check_connectivity() {
for ((i=1; i<=RETRIES; i++)); do
timestamp=$(date "+%Y-%m-%d %H:%M:%S")
ttfb=$(curl -o /dev/null --max-time $CURL_TIMEOUT --connect-timeout $CURL_TIMEOUT -s -w '%{time_starttransfer}\n' $URL)
t=$(echo "scale=0; $ttfb*1000/1" | bc)
t_int=$(printf "%.0f" "$t")
http_code=$(curl -o /dev/null --max-time $CURL_TIMEOUT --connect-timeout $CURL_TIMEOUT -s -w '%{http_code}\n' $URL)
# Ignore 0 ms latencies
if [ "$ttfb" == "0" ]; then
echo "Attempt $i/$RETRIES: Ignoring 0 ms latency."
sleep $RETRY_DELAY
continue
fi
if [ "$http_code" -eq 204 ]; then
if [ "$t_int" -gt 1000 ]; then
echo "😐😐😐 [$timestamp] Internet is slow! Time to first byte (latency): $t ms"
else
echo "😺😺😺 [$timestamp] Internet is up. Time to first byte (latency): $t ms"
fi
return
else
echo "Attempt $i/$RETRIES: 😑😑😑 [$timestamp] Internet is down or unstable."
if [ "$i" -lt "$RETRIES" ]; then
sleep $RETRY_DELAY
fi
fi
done
echo "😑😑😑 [$timestamp] Internet is down or unstable after $RETRIES retries."
}
# Continuously check connectivity
while true; do
check_connectivity
sleep $INTERVAL
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment