Skip to content

Instantly share code, notes, and snippets.

@benton
Last active Oct 28, 2017
Embed
What would you like to do?
Ping an IP forever and report its reachability
#!/usr/bin/env bash
# pings an IP address forever and tracks whether it is accessible
# logs the connection's state change to $STDOUT
ip='8.8.8.8'
track_attempts=5
failure_threshold=3
delay=1
# track state
state='up'
failures=0
echo "Pinging ${ip} forever (CTRL-C / SIGTERM to quit)..."
while true ; do
if ping -c 1 $ip >/dev/null 2>&1 ; then
# ping succeeded
if [ "$failures" -gt "0" ] ; then let failures-=1 ; fi
else # ping failed
if [ "$failures" -lt "$track_attempts" ] ; then let failures+=1 ; fi
fi
# echo "Failures in the last $track_attempts attempts: $failures"
# detect state change...
if [ "$failures" -gt "$failure_threshold" ] ; then
if [ "$state" == 'up' ] ; then
echo "Connection has gone down at $(date +'%Y-%m-%d %H:%M:%S %Z')!"
state='down'
fi
else
if [ "$state" == 'down' ] ; then
echo "Connection has come up at $(date +'%Y-%m-%d %H:%M:%S %Z')!"
state='up'
fi
fi
sleep $delay
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment