Skip to content

Instantly share code, notes, and snippets.

@ivanstepanovftw
Created December 19, 2022 13:36
Show Gist options
  • Save ivanstepanovftw/27376da49cc276b6b6638e7c3bddbb51 to your computer and use it in GitHub Desktop.
Save ivanstepanovftw/27376da49cc276b6b6638e7c3bddbb51 to your computer and use it in GitHub Desktop.
Is WiFi or internet is down?
#/usr/bin/bash
ping_tolerance=1
ok_retry_time=1
fail_retry_time=1
log() {
echo "$(date) - $@"
}
check_internet() {
local route="$(ip route)"
[[ -z "$route" ]] && echo "No route found" && return 1
local default_gateway=$(echo "$route" | grep default | awk '{print $3}')
[[ -z "$default_gateway" ]] && echo "No default gateway found" && return 2
local ping_gateway=$(ping -c1 -w$ping_tolerance $default_gateway | grep "1 received")
[[ -z "$ping_gateway" ]] && echo "Failed to ping default gateway" && return 3
local ping_google=$(ping -c1 -w$ping_tolerance google.com | grep "1 received")
[[ -z "$ping_google" ]] && echo "Failed to ping google.com" && return 4
return 0
}
# Main loop
while true; do
internet_status=$(check_internet)
if [[ $? == 0 ]]; then
log "Internet is up"
# Some optimizations
while [[ -n "$(ping -c1 -w$ping_tolerance google.com | grep "1 received")" ]]; do
sleep $ok_retry_time
done
else
log "Internet is down: $internet_status"
echo -n $'\a'
sleep $fail_retry_time
fi
done
@ivanstepanovftw
Copy link
Author

ivanstepanovftw commented Dec 27, 2022

No route found

Ensure you are connected to your router

No default gateway found

Ensure you are connected to your router

Failed to ping default gateway

Check your router

Failed to ping google.com

Provider issue

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment