You are here
Two simple ways a script can detect if it's online
Liraz Siri - Mon, 2014/09/01 - 08:15 -
3 comments
I didn't want installation of one of TurnKey's components to freeze up too long if it was installed offline so I looked for a nice way to detect that without bringing in additional dependencies.
Two methods stood out...
-
ping Google DNS servers: one second constant delay, regardless if you're online or off:
# will be true if we're online. Will send 5 packets total. is_online() { ping -w 1 -i 0.2 8.8.8.8 > /dev/null }
-
try to resolve a hostname: this will return very quickly if online, 2-3 seconds if we're not, assuming we pass the right args to "host":
is_online() { if 2>&1 host -h | grep -q -- -W; then command="host -W 1" else command="host -s 1" fi $command pool.ntp.org >& /dev/null }
Since I figured we'd be online more often then not I optimized for that and chose the second method.
Comments
I like it!
Thanks for the suggestion Tom. Your one-liner is an improvement. I didn't realize you could use getent for this. Nice!
Pages
Add new comment