Celeb Glow
updates | April 01, 2026

How can I check Internet connectivity in a console?

Is there an easy way to check Internet connectivity from console? I am trying to play around in a shell script. One idea I seem is to wget --spider and check the HTTP response code to interpret if the Internet connection is working fine. But I think there must be easy way without the need of checking a site that never crash ;)

Edit: Seems like there can be a lot of factors which can be individually examined, good thing. My intention at the moment is to check if my blog is down. I have setup cron to check it every minute. For this, I am checking the HTTP response code of wget --spider to my blog. If its not 200, it notifies me (I believe this will be better than just pinging it, as the site may under be heavy load and may be timing out or respond very late). Now yesterday, there was some problem with my Internet. LAN was connected fine but just I couldn't access any site. So I keep on getting notifications as the script couldn't find 200 in the wget response. Now I want to make sure that it displays me notification when I do have internet connectivity.

So, checking for DNS and LAN connectivity is a bit overkill for me as I don't have that much specific need to figure out what problem it is. So what do you suggest how I do it?

Here is my script to keep checking downtime for my blog:

#!/bin/bash
# Sending the output of the wget in a variable and not what wget fetches
RESULT=`wget --spider 2>&1`
FLAG=0
# Traverse the string considering it as an array of words
for x in $RESULT; do if [ "$x" = '200' ]; then FLAG=1 # This means all good fi
done
if [ $FLAG -eq '0' ]; then # A good point is to check if the internet is working or not # Check if we have internet connectivity by some other site RESULT=`wget --spider 2>&1` for x in $RESULT; do if [ "$x" = '200' ]; then FLAG=1 # This means we do have internet connectivity and the blog is actually down fi done if [ $FLAG -eq '1' ]; then DISPLAY=:0 notify-send -t 2000 -i /home/ashfame/Dropbox/Ubuntu/icons/network-idle.png "Downtime Alert!" " is down." fi
fi
exit

This way I need to check for internet connectivity only where there is an issue with my blog response code. Its a bit heavy (as I am not using ping) but should not give any false positives. Right? Also how can I randomize pinging to a different site everytime, like facebook, google, yahoo etc. Also (I was trying to avoid any I/O) I can write to a log file by which I can check the count of downtime checks and then skip further checks till the site is down or cause longer checks (10mins instead of every min). What do you think?

2

12 Answers

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
if [ "$?" != 0 ]; then echo "Website failed!" | mail -s "Website down"
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 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.

10

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.

1

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
fi
2

Checking to see if a site is up is usually done with a monitoring tool like nagios. This will continuously monitor the site, and can notify you of outages.

When checking if the Internet is up from the command line I run through a number of steps:

  • Check Internet is up ping google.com (checks DNS and known reachable site).
  • Check web site is up use wget or w3m to fetch page.

If Internet is not up diagnose outward.

  • Check gateway is pingable. (Check ifconfig for gateway address.)
  • Check DNS servers are pingable. (Check /etc/resolv.conf for addresses.)
  • Check to see if firewall is blocking. (Check /var/log/syslog as I log blocks.)

If Internet is up but site is down check with w3m replacing example.com with the site that appears down. Use wget, lynx, or which ever command line browser you have available if you don't have the w3m browser installed.

5

This is the shell srcript I'm using to test for internet connectivity:

alarm.sh

#! /bin/bash
if curl --silent --head | egrep "20[0-9] Found|30[0-9] Found" >/dev/null
then echo Internet status: OK
else echo Internet status: ERROR mpg321 alarm.mp3 &> /dev/null
fi
sleep 60
clear
./alarm.sh

You will need to install curl and mpg321

sudo apt-get install curl mpg321

You will need a .mp3 sound file renamed to alarm.mp3 in the same folder if you want audible alarm functionality. Finally configure website URL and egrep to your needs.

5

I am using this method:

if curl -s --head --request GET | grep "200 OK" > /dev/null ; then echo "Internet is present"
else echo "Internet isn't present"
fi

It will try to connect to a well-known website and if it can connect to it then we will assume there is the internet.

Checking whether internet is working

sudo nm-tool | grep "State: connected" | wc -l

From output (excerpt):

1 #System is connected to internet

However, as mentioned by others, this is not telling whether you really have connectivity or not. Eg. You could be connected to the router and router is not necessarily connected to internet.

3

I needed help with the same question, and I got my answer this way:

echo $(nm-online) $? connection problems
2

Checking whether Internet is working is not so trivial. ping is ICMP, so it might work even if the web proxy is down. Something similar occurs with DNS if you test with an IP.

Since my Internet connection is unstable I created this script (based on this one) that makes a gentle chord sound to call me, and also uses Ubuntu notify when the Internet connection comes back:

#!/bin/bash
hash play 2>&- || { echo >&2 "I require «play» but it's not installed. Try apt-get install sox. Aborting."; exit 1; }
WGET="`which wget`"
URL=""
delay=3;
noConnectionMessage="No connection, trying again in $delay seconds...";
connectionMessage="WE HAVE INTERNET! :) Trying again in $delay seconds...";
echo "INTERNET TESTER: Type Ctrl+C to quit";
rm --force /tmp/index.site
function playSound { time=1; # Time played if [ `sox --version| grep -oP "v[0-9.]+" | sed "s/[v.]//g"` -lt 1431 ]; then #analize sox version, if greater than v14.3.1 can use pluck play -q -n synth $time sine; else play -q -n synth $time pluck $1; #for i in G4 G4 G4 E4;do play -n synth 0.1 pluck $i repeat 2;done # You can play with something like this also :) (first three notes from Beethoven 5th symphony) fi
}
while [ 1 -eq 1 ]; do $WGET -q --tries=10 --timeout=2 $URL -O /tmp/index.site &> /dev/null if [ ! -s /tmp/index.site ];then echo $noConnectionMessage; #playSound E2 sleep 1; else #~ zenity --warning --text "ADDRESS is back" notify-send -i "notification-network-wireless-full" "Connection state:" "$connectionMessage"; echo $connectionMessage; playSound E3 fi sleep $delay;
done
exit 0;

I was looking for a script that would continuously test my internet connection, that would be started whenever my server was up and I made this:

  1. First, install fping

    apt-get install fping
  2. Create an init script in the /etc/init.d folder with the following content (I called it testcon)

    #!/bin/bash
    PIDFILE=/var/run/testcon.pid
    . /lib/lsb/init-functions
    case "$1" in start) log_daemon_msg "Starting internet connection tester" /etc/init.d/testcond & echo $! > $PIDFILE log_end_msg $? ;; stop) log_daemon_msg "Stopping internet connection tester" PID=$(cat $PIDFILE) kill -9 "$PID" log_end_msg $? ;; *) echo "Usage: /etc/init.d/testcon {start|stop}" exit 1 ;;
    esac
    exit 0
  3. Create a script in the /etc/init.d folder with the following content (I called it testcond)

    #echo Computer starting or testing daemon init
    while [ "$itest" == "" ]
    do #wait 5 seconds sleep 5 itest=$(fping 8.8.8.8 | grep alive)
    done
    date | mail -s "Server is up and Internet is online"
    #loop forever
    while [ "1" == "1" ]
    do itest=$(fping 8.8.8.8 | grep alive) #if internet is down if [ "$itest" == "" ] then #echo Internet is down #log time it was found down current_time=$(date) echo "Internet was found down @ $current_time" >> /mnt/data/Server/internet_log.txt #loop until it is back while [ "$itest" == "" ] do #wait 60 seconds sleep 60 itest=$(fping 8.8.8.8 | grep alive) # test the internet done #when it is back current_time=$(date) echo "Internet is back @ $current_time" >> /mnt/data/Server/internet_log.txt body=$(tail -2 /mnt/data/Server/internet_log.txt) echo "$body" | mail -s "Internet is back online" fi #echo Internet is online #wait 60 seconds sleep 60 done
  4. Then I run the commands below to add to the start-up:

    sudo update-rc.d testcon defaults
    sudo update-rc.d testcon enable
  5. Reboot

I was faced with random droppings of Wi-Fi connections by my Broadcom BCM94331CD chip. I devised the following bash script (infinite loop) checking each second if the Internet Wi-Fi connection is up and running. Other command line proposed here will wait for at least 5 to 10 seconds before closing with a status i.e. ping. In the mean time I am looking for a definitive solution as well.

From results on askubuntu, I will have to purge the bcmwl-kernel-source package as I use firmware-b43-installer and b43-fwcutter.

Thanks everyone for their suggestions (above).

This script needs to be added in the Start-Up Programs and don't need super user privilege to run as well.

#!/bin/bash
#
# Check if Wi-Fi is disabled e.g. 'out of range'
# If so quickly re-enable Wi-Fi
# Due to a problem with Broadcom proprietary driver in package firmware-b43-installer
# Script is part of Start-Up programs
# Stored in /usr/local/bin/
# Infinite loop checking every second if Wi-Fi is up and running
while true; do # if [[ $(nmcli -f STATE -t g) != 'connected' ]]; then # Disable and Re-Enable Wi-Fi as the Wi-Fi is now 'out of range' (disconnected) nmcli radio wifi off nmcli radio wifi on fi sleep 1
done

I have been reading this but I see no mention on using monit to check the same.

In monit, the principle of ping is applied when you set something like this in monitrc file:

check host OnlineStatus with address 1.1.1.1

I used CloudFlare 1.1.1.1, but of course you can use domain or other ip as prescribed in monit website and its wiki. You then can set what it should do if that ping failed, for instance:

 if failed icmp type echo count 3 with timeout 10 seconds then exec "command-or- script"

Whether this is to check your server is online (connected to the internet) or certain services like web or mail server are still working or even restart them if they failed, warning you via email, you can rely on monit, that is if you installed in your server and configured it accordingly.

3

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy