How can I check Internet connectivity in a console?
Checking whether specific website is up
First, multiple good online monitoring services are available. To pick one, Pingdom includes free account for monitoring one target. (Disclaimer: I am not affiliated with Pingdom in any way).
Second, using wget --spider
for your own script is a good idea. You'll get some false positives when your computer is down, or when your DNS server is not working. Checking the return code is straightforward way to do implement this:
wget --spider --quiet http://example.com
if [ "$?" != 0 ]; then
echo "Website failed!" | mail -s "Website down" [email protected]
fi
Yet again, there are shortcomings in this approach. If your provider has cached your DNS record, but the DNS server is down, others can't access your site even though monitoring says everything is fine. You can write short workaround with host
, for example host example.com <your dns server IP>
. That will return error if DNS server is not responding, even if OpenDNS or your own provider's DNS server works fine.
Checking whether internet is working
There isn't really easy way to handle this in every case.
You can for example run ping -c1
on multiple well known sites (for example www.google.com, facebook.com and ping.funet.fi) and check return codes to determine whether any destination is reachable. You can automatically check return code by using variable $?
. Parameter -c1
is limiting number of ping packets to one.
You may encounter problems with some public wifis when there is a login gateway that redirects all pings and HTTP requests. If so, you may get ping responses and non-error HTTP status codes, even when you can't access any other sites.
If you want to check cable state, you can use
sudo ethtool eth0
From output (excerpt):
Speed: 1000Mb/s
Duplex: Full
Port: Twisted Pair
Link detected: yes
However, this is not telling whether you really have connectivity or not, just whether cable is connected and something is on other end.
I'm using this method...
if [[ "$(ping -c 1 8.8.8.8 | grep '100% packet loss' )" != "" ]]; then echo "Internet isn't present" exit 1 else echo "Internet is present" wget www.site.com fi
I just used
nm-online
which pauses until a network connection is present by network manager. Worked well. You can do other stuff with it too.