Skip to content

Instantly share code, notes, and snippets.

@bfred-it bfred-it/README.md
Last active Mar 28, 2019

Embed
What would you like to do?
OS X connection monitor

Connection monitor

Note: if you need a simple connection icon, check out BitBar and its internet checker plugin.

This program notifies you when Internet goes down and when it comes back up.

It pings Google's DNS every 4 seconds; when a ping fails it quickly tries a few more times and switches to downtime mode. When Internet is available again, the cycle restarts.

Tools used

  • bash
  • ping
  • osascript (AppleScript, for the OSX notifications)

Notes

Remove lines with osascript to make it compatible outside OS X

Alternatives

http://antirez.com/iconping/

Author

Twitter, more gists, blog

#!/bin/bash
# Details: https://gist.github.com/bfred-it/7a269ca212faced83e60
# License: WTFPL
# By: Federico Brigante
#config
retries=6
check_interval=4 #seconds
check_interval_hyper=0.2
check_interval_down=0.5
ping_timeout=1 #integers only, ping's fault
offline_message="❌ You are offline"
online_message="✅ You are back online!"
#program
echo $(date +"%T") "Hi. I will notify you when the internet goes down"
while true; do
status=$retries
# check connectivity every 4 seconds
while ! [ "$status" -eq 0 ]; do
if ! ping -c 1 -t $ping_timeout -q 8.8.8.8 > /dev/null 2>&1; then
echo $(date +"%T") "Ping timed out"
# echo $(date +"%T") "You may be offline. Tries left:" $status
let "status -= 1"
sleep $check_interval_hyper
else
# if ! [[ "$status" -eq $retries ]]; then
# echo 'It was only temporary. You are online'
# fi
status=$retries # restore counter
sleep $check_interval
fi
done
# if it reaches this point, you are offline
echo $(date +"%T") $offline_message
offline_since=$(date +"%s")
osascript -e "display notification \"\" with title \"$offline_message\""
while ! ping -c 1 -t $ping_timeout -q 8.8.8.8 > /dev/null 2>&1; do
sleep $check_interval_down
done
# if it reaches this point, you are back online
online_since=$(date +"%s")
downtime_duration=$(($online_since-$offline_since))
echo $(date +"%T") $online_message 'It lasted' $downtime_duration 'seconds'
osascript -e "display notification \"You were offline for $downtime_duration seconds\" with title \"$online_message\""
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.