I highly recommend against using ping
to determine connectivity. There are too many network admins that disable ICMP (the protocol it uses) due to worries about ping flood attacks originating from their networks.
Instead, I use a quick test of a reliable server on a port you can expect to be open:
if nc -zw1 google.com 443; then
echo "we have connectivity"
fi
This uses netcat (nc
) in its port scan mode, a quick poke (-z
is zero-I/O mode [used for scanning]) with a quick timeout (-w 1
waits at most one second, though Apple OS X users may need to use -G 1
instead). It checks Google on port 443 (HTTPS).
I've used HTTPS rather than HTTP as an effort to protect against captive portals and transparent proxies which can answer on port 80 (HTTP) for any host. This is less likely when using port 443 since there would be a certificate mismatch, but it does still happen.
If you want to proof yourself against that, you'll need to validate the security on the connection:
test=google.com
if nc -zw1 $test 443 && echo |openssl s_client -connect $test:443 2>&1 |awk '
$1 == "SSL" && $2 == "handshake" { handshake = 1 }
handshake && $1 == "Verification:" { ok = $2; exit }
END { exit ok != "OK" }'
then
echo "we have connectivity"
fi
This checks for a connection (rather than waiting for openssl to time out) and then makes the SSL handshake, keying on the verification phase. It silently exits ("true") if the verification was "OK" or else exits with an error ("false"), then we report the finding.
The awk code analyzes the output of openssl
line by line:
- If the first word of the line is "SSL" and the second is "Verification", set
handshake
to 1
- If
handshake
is set and the first word of the line is "Verification",
then save the second word (the verification status) in ok
and stop reading
- Exit with a value of
0
(true) if the verification status was OK
, or else exit with 1
(false).
We use !=
here because shell exit codes are reversed
(An awk oddity: Running exit
while reading lines will simply stop reading lines and enter the END
condition, from which you can truly exit
.)