How can I check Internet connectivity in a console?












29















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 http://www.google.co.in/ 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 http://blog.ashfame.com 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 http://www.facebook.com 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!" "http://blog.ashfame.com/ 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?










share|improve this question

























  • "Internet connectivity" does not have a clear definition, you can only test the connectivity to a specific service or set of services. If you mean "LAN" connectivity a good option is to ping your network gateway.

    – João Pinto
    Feb 24 '11 at 23:43











  • In layman terms, I would define Internet connectivity is if you can access internet. Problem can by anything in between. I just need to differentiate between if its working fine or there is problem out of the set of problem that can be responsible. I hope I made myself clear. :)

    – Ashfame
    Feb 25 '11 at 6:28
















29















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 http://www.google.co.in/ 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 http://blog.ashfame.com 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 http://www.facebook.com 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!" "http://blog.ashfame.com/ 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?










share|improve this question

























  • "Internet connectivity" does not have a clear definition, you can only test the connectivity to a specific service or set of services. If you mean "LAN" connectivity a good option is to ping your network gateway.

    – João Pinto
    Feb 24 '11 at 23:43











  • In layman terms, I would define Internet connectivity is if you can access internet. Problem can by anything in between. I just need to differentiate between if its working fine or there is problem out of the set of problem that can be responsible. I hope I made myself clear. :)

    – Ashfame
    Feb 25 '11 at 6:28














29












29








29


8






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 http://www.google.co.in/ 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 http://blog.ashfame.com 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 http://www.facebook.com 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!" "http://blog.ashfame.com/ 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?










share|improve this question
















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 http://www.google.co.in/ 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 http://blog.ashfame.com 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 http://www.facebook.com 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!" "http://blog.ashfame.com/ 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?







command-line networking internet






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 9 '18 at 6:48









muru

1




1










asked Feb 24 '11 at 20:42









AshfameAshfame

1,61472742




1,61472742













  • "Internet connectivity" does not have a clear definition, you can only test the connectivity to a specific service or set of services. If you mean "LAN" connectivity a good option is to ping your network gateway.

    – João Pinto
    Feb 24 '11 at 23:43











  • In layman terms, I would define Internet connectivity is if you can access internet. Problem can by anything in between. I just need to differentiate between if its working fine or there is problem out of the set of problem that can be responsible. I hope I made myself clear. :)

    – Ashfame
    Feb 25 '11 at 6:28



















  • "Internet connectivity" does not have a clear definition, you can only test the connectivity to a specific service or set of services. If you mean "LAN" connectivity a good option is to ping your network gateway.

    – João Pinto
    Feb 24 '11 at 23:43











  • In layman terms, I would define Internet connectivity is if you can access internet. Problem can by anything in between. I just need to differentiate between if its working fine or there is problem out of the set of problem that can be responsible. I hope I made myself clear. :)

    – Ashfame
    Feb 25 '11 at 6:28

















"Internet connectivity" does not have a clear definition, you can only test the connectivity to a specific service or set of services. If you mean "LAN" connectivity a good option is to ping your network gateway.

– João Pinto
Feb 24 '11 at 23:43





"Internet connectivity" does not have a clear definition, you can only test the connectivity to a specific service or set of services. If you mean "LAN" connectivity a good option is to ping your network gateway.

– João Pinto
Feb 24 '11 at 23:43













In layman terms, I would define Internet connectivity is if you can access internet. Problem can by anything in between. I just need to differentiate between if its working fine or there is problem out of the set of problem that can be responsible. I hope I made myself clear. :)

– Ashfame
Feb 25 '11 at 6:28





In layman terms, I would define Internet connectivity is if you can access internet. Problem can by anything in between. I just need to differentiate between if its working fine or there is problem out of the set of problem that can be responsible. I hope I made myself clear. :)

– Ashfame
Feb 25 '11 at 6:28










11 Answers
11






active

oldest

votes


















27














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" your_email@provider.tld
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.






share|improve this answer


























  • This is totally for my setup, working on Always-ON Ethernet. But glad that you pointed out how it won't work correctly in some cases. Also I believe pinging would be faster than wget. What do you think? and if I am checking for a 200 status code anywhere, I would rather be just pinging it. Right? or there is something that I should know?

    – Ashfame
    Feb 25 '11 at 6:39








  • 2





    ping is faster, and better, because other end won't be angry for you. ping is pretty safe, but even that do not guarantee that you can open web pages. Also, it is possible that firewall is blocking ping but allowing HTTP requests.

    – Olli
    Feb 25 '11 at 7:18






  • 1





    Pinging a well known dns server like 4.2.2.2 is also useful in case you have net connectivity but broken dns.

    – djeikyb
    Feb 25 '11 at 8:56











  • For DNS checking you can of course use host (DNS query). It's very fast also.

    – Olli
    Feb 25 '11 at 9:38











  • Thanks for your response @Olli & @djeikyb I have updated the question, please take a look

    – Ashfame
    Feb 25 '11 at 12:57





















7














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





share|improve this answer


























  • I got different results for ping -c 1 8.8.8.8 and ping -c 1 www.google.com. How is that?

    – MERose
    Mar 3 '15 at 13:42






  • 1





    Note that this will fail in China and other countries that block Google

    – Tom J Nowell
    Jul 14 '18 at 14:24



















5














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.






share|improve this answer































    5














    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 http://isup.me/example.com 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.






    share|improve this answer


























    • Thanks for your suggestion! Does my script covers the basic requirement of checking and alerting me when my site is down? And it will be quiet in case there is some Internet connectivity problem

      – Ashfame
      Feb 27 '11 at 16:35













    • It looks like your script will do what you want. You could include the wget command in the if statement as if ! wget --spider http:///example.com; then.

      – BillThor
      Feb 27 '11 at 16:58











    • you mean wget always return 1 for 200 HTTP response code?

      – Ashfame
      Feb 27 '11 at 20:08











    • I mean the test [ $? != 0 ] is the the same as the test ! command. wget is documented to return 0 on success and not 0 for failure. The if behaves identically which ever way you code it. If wget returns failure on a 200 response, the test will fail either way your write it. The same if it returns 0 for a response code other than 200.

      – BillThor
      Feb 27 '11 at 23:25











    • Thanks! That would make the script smaller and easy to understand.

      – Ashfame
      Feb 28 '11 at 5:24



















    3














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



    alarm.sh



    #! /bin/bash

    if curl --silent --head http://www.google.com/ |
    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.






    share|improve this answer


























    • This works perfectly even when the user is behind a captive portal and has not logged in.

      – Ashhar Hasan
      May 8 '17 at 13:02











    • You can use egrep -q instead of egrep ... > /dev/null

      – wjandrea
      Nov 28 '17 at 2:26











    • Why does the script call itself instead of just using a while loop?

      – wjandrea
      Nov 28 '17 at 2:26











    • Oh wait, it doesn't call itself. It calls a script called alarm.sh in the wd, so if you call this script from a different dir, it will either error, or if there's a script called alarm.sh in the wd, it will call that instead. So that's bad practice. You could use "$0" instead, but a while loop would be better.

      – wjandrea
      Nov 28 '17 at 2:28













    • "Why does the script call itself instead of just using a while loop? " : Because I was a noobs when I made that post and yes that script was calling itself.

      – 01BTC10
      Dec 1 '17 at 17:19





















    2














    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.






    share|improve this answer



















    • 2





      nm-tool has been removed in Ubuntu 15.04+, but you can use nmcli instead. E.g. [[ $(nmcli -f STATE -t g) = connected ]]

      – Six
      Jan 27 '16 at 15:15











    • @Six nmcli -f STATE -t nm the good thing is being independent of web sites!

      – Aquarius Power
      Jan 31 '16 at 2:13













    • Note that nm-tool and nmcli will tell you only whether or not you're connected to local network, i.e. whether or not you're connected to your home wifi/ethernet. It won't tell you whether or not you can reach anything beyond your local network, i.e. internet.

      – Sergiy Kolodyazhnyy
      Nov 28 '17 at 3:27



















    1














    I am using this method:



    if curl -s --head  --request GET www.google.com | 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.






    share|improve this answer































      0














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



      echo $(nm-online) $? connection problems





      share|improve this answer
























      • how does this work?

        – wjandrea
        Nov 28 '17 at 2:31











      • It is just checking the status (one character) of the nm-online command... It will return 0 if everything is fine. Usual in all UNIX shells.

        – Antonio
        Mar 3 '18 at 23:16





















      0














      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="http://www.google.com"
      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;





      share|improve this answer

































        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" your_email@gmail.com

          #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" your_email@gmail.com
          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







        share|improve this answer

































          0














          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
          # https://askubuntu.com/questions/27954/how-can-i-check-internet-connectivity-in-a-console
          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





          share|improve this answer























            Your Answer








            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "89"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2faskubuntu.com%2fquestions%2f27954%2fhow-can-i-check-internet-connectivity-in-a-console%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            11 Answers
            11






            active

            oldest

            votes








            11 Answers
            11






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            27














            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" your_email@provider.tld
            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.






            share|improve this answer


























            • This is totally for my setup, working on Always-ON Ethernet. But glad that you pointed out how it won't work correctly in some cases. Also I believe pinging would be faster than wget. What do you think? and if I am checking for a 200 status code anywhere, I would rather be just pinging it. Right? or there is something that I should know?

              – Ashfame
              Feb 25 '11 at 6:39








            • 2





              ping is faster, and better, because other end won't be angry for you. ping is pretty safe, but even that do not guarantee that you can open web pages. Also, it is possible that firewall is blocking ping but allowing HTTP requests.

              – Olli
              Feb 25 '11 at 7:18






            • 1





              Pinging a well known dns server like 4.2.2.2 is also useful in case you have net connectivity but broken dns.

              – djeikyb
              Feb 25 '11 at 8:56











            • For DNS checking you can of course use host (DNS query). It's very fast also.

              – Olli
              Feb 25 '11 at 9:38











            • Thanks for your response @Olli & @djeikyb I have updated the question, please take a look

              – Ashfame
              Feb 25 '11 at 12:57


















            27














            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" your_email@provider.tld
            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.






            share|improve this answer


























            • This is totally for my setup, working on Always-ON Ethernet. But glad that you pointed out how it won't work correctly in some cases. Also I believe pinging would be faster than wget. What do you think? and if I am checking for a 200 status code anywhere, I would rather be just pinging it. Right? or there is something that I should know?

              – Ashfame
              Feb 25 '11 at 6:39








            • 2





              ping is faster, and better, because other end won't be angry for you. ping is pretty safe, but even that do not guarantee that you can open web pages. Also, it is possible that firewall is blocking ping but allowing HTTP requests.

              – Olli
              Feb 25 '11 at 7:18






            • 1





              Pinging a well known dns server like 4.2.2.2 is also useful in case you have net connectivity but broken dns.

              – djeikyb
              Feb 25 '11 at 8:56











            • For DNS checking you can of course use host (DNS query). It's very fast also.

              – Olli
              Feb 25 '11 at 9:38











            • Thanks for your response @Olli & @djeikyb I have updated the question, please take a look

              – Ashfame
              Feb 25 '11 at 12:57
















            27












            27








            27







            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" your_email@provider.tld
            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.






            share|improve this answer















            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" your_email@provider.tld
            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.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Apr 8 '18 at 18:36

























            answered Feb 24 '11 at 20:47









            OlliOlli

            6,93613040




            6,93613040













            • This is totally for my setup, working on Always-ON Ethernet. But glad that you pointed out how it won't work correctly in some cases. Also I believe pinging would be faster than wget. What do you think? and if I am checking for a 200 status code anywhere, I would rather be just pinging it. Right? or there is something that I should know?

              – Ashfame
              Feb 25 '11 at 6:39








            • 2





              ping is faster, and better, because other end won't be angry for you. ping is pretty safe, but even that do not guarantee that you can open web pages. Also, it is possible that firewall is blocking ping but allowing HTTP requests.

              – Olli
              Feb 25 '11 at 7:18






            • 1





              Pinging a well known dns server like 4.2.2.2 is also useful in case you have net connectivity but broken dns.

              – djeikyb
              Feb 25 '11 at 8:56











            • For DNS checking you can of course use host (DNS query). It's very fast also.

              – Olli
              Feb 25 '11 at 9:38











            • Thanks for your response @Olli & @djeikyb I have updated the question, please take a look

              – Ashfame
              Feb 25 '11 at 12:57





















            • This is totally for my setup, working on Always-ON Ethernet. But glad that you pointed out how it won't work correctly in some cases. Also I believe pinging would be faster than wget. What do you think? and if I am checking for a 200 status code anywhere, I would rather be just pinging it. Right? or there is something that I should know?

              – Ashfame
              Feb 25 '11 at 6:39








            • 2





              ping is faster, and better, because other end won't be angry for you. ping is pretty safe, but even that do not guarantee that you can open web pages. Also, it is possible that firewall is blocking ping but allowing HTTP requests.

              – Olli
              Feb 25 '11 at 7:18






            • 1





              Pinging a well known dns server like 4.2.2.2 is also useful in case you have net connectivity but broken dns.

              – djeikyb
              Feb 25 '11 at 8:56











            • For DNS checking you can of course use host (DNS query). It's very fast also.

              – Olli
              Feb 25 '11 at 9:38











            • Thanks for your response @Olli & @djeikyb I have updated the question, please take a look

              – Ashfame
              Feb 25 '11 at 12:57



















            This is totally for my setup, working on Always-ON Ethernet. But glad that you pointed out how it won't work correctly in some cases. Also I believe pinging would be faster than wget. What do you think? and if I am checking for a 200 status code anywhere, I would rather be just pinging it. Right? or there is something that I should know?

            – Ashfame
            Feb 25 '11 at 6:39







            This is totally for my setup, working on Always-ON Ethernet. But glad that you pointed out how it won't work correctly in some cases. Also I believe pinging would be faster than wget. What do you think? and if I am checking for a 200 status code anywhere, I would rather be just pinging it. Right? or there is something that I should know?

            – Ashfame
            Feb 25 '11 at 6:39






            2




            2





            ping is faster, and better, because other end won't be angry for you. ping is pretty safe, but even that do not guarantee that you can open web pages. Also, it is possible that firewall is blocking ping but allowing HTTP requests.

            – Olli
            Feb 25 '11 at 7:18





            ping is faster, and better, because other end won't be angry for you. ping is pretty safe, but even that do not guarantee that you can open web pages. Also, it is possible that firewall is blocking ping but allowing HTTP requests.

            – Olli
            Feb 25 '11 at 7:18




            1




            1





            Pinging a well known dns server like 4.2.2.2 is also useful in case you have net connectivity but broken dns.

            – djeikyb
            Feb 25 '11 at 8:56





            Pinging a well known dns server like 4.2.2.2 is also useful in case you have net connectivity but broken dns.

            – djeikyb
            Feb 25 '11 at 8:56













            For DNS checking you can of course use host (DNS query). It's very fast also.

            – Olli
            Feb 25 '11 at 9:38





            For DNS checking you can of course use host (DNS query). It's very fast also.

            – Olli
            Feb 25 '11 at 9:38













            Thanks for your response @Olli & @djeikyb I have updated the question, please take a look

            – Ashfame
            Feb 25 '11 at 12:57







            Thanks for your response @Olli & @djeikyb I have updated the question, please take a look

            – Ashfame
            Feb 25 '11 at 12:57















            7














            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





            share|improve this answer


























            • I got different results for ping -c 1 8.8.8.8 and ping -c 1 www.google.com. How is that?

              – MERose
              Mar 3 '15 at 13:42






            • 1





              Note that this will fail in China and other countries that block Google

              – Tom J Nowell
              Jul 14 '18 at 14:24
















            7














            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





            share|improve this answer


























            • I got different results for ping -c 1 8.8.8.8 and ping -c 1 www.google.com. How is that?

              – MERose
              Mar 3 '15 at 13:42






            • 1





              Note that this will fail in China and other countries that block Google

              – Tom J Nowell
              Jul 14 '18 at 14:24














            7












            7








            7







            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





            share|improve this answer















            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






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Feb 28 '15 at 15:09









            MERose

            206518




            206518










            answered Oct 14 '13 at 9:18









            bais baisbais bais

            7111




            7111













            • I got different results for ping -c 1 8.8.8.8 and ping -c 1 www.google.com. How is that?

              – MERose
              Mar 3 '15 at 13:42






            • 1





              Note that this will fail in China and other countries that block Google

              – Tom J Nowell
              Jul 14 '18 at 14:24



















            • I got different results for ping -c 1 8.8.8.8 and ping -c 1 www.google.com. How is that?

              – MERose
              Mar 3 '15 at 13:42






            • 1





              Note that this will fail in China and other countries that block Google

              – Tom J Nowell
              Jul 14 '18 at 14:24

















            I got different results for ping -c 1 8.8.8.8 and ping -c 1 www.google.com. How is that?

            – MERose
            Mar 3 '15 at 13:42





            I got different results for ping -c 1 8.8.8.8 and ping -c 1 www.google.com. How is that?

            – MERose
            Mar 3 '15 at 13:42




            1




            1





            Note that this will fail in China and other countries that block Google

            – Tom J Nowell
            Jul 14 '18 at 14:24





            Note that this will fail in China and other countries that block Google

            – Tom J Nowell
            Jul 14 '18 at 14:24











            5














            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.






            share|improve this answer




























              5














              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.






              share|improve this answer


























                5












                5








                5







                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.






                share|improve this answer













                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.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Dec 25 '16 at 23:03









                ntsecretsntsecrets

                5111




                5111























                    5














                    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 http://isup.me/example.com 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.






                    share|improve this answer


























                    • Thanks for your suggestion! Does my script covers the basic requirement of checking and alerting me when my site is down? And it will be quiet in case there is some Internet connectivity problem

                      – Ashfame
                      Feb 27 '11 at 16:35













                    • It looks like your script will do what you want. You could include the wget command in the if statement as if ! wget --spider http:///example.com; then.

                      – BillThor
                      Feb 27 '11 at 16:58











                    • you mean wget always return 1 for 200 HTTP response code?

                      – Ashfame
                      Feb 27 '11 at 20:08











                    • I mean the test [ $? != 0 ] is the the same as the test ! command. wget is documented to return 0 on success and not 0 for failure. The if behaves identically which ever way you code it. If wget returns failure on a 200 response, the test will fail either way your write it. The same if it returns 0 for a response code other than 200.

                      – BillThor
                      Feb 27 '11 at 23:25











                    • Thanks! That would make the script smaller and easy to understand.

                      – Ashfame
                      Feb 28 '11 at 5:24
















                    5














                    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 http://isup.me/example.com 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.






                    share|improve this answer


























                    • Thanks for your suggestion! Does my script covers the basic requirement of checking and alerting me when my site is down? And it will be quiet in case there is some Internet connectivity problem

                      – Ashfame
                      Feb 27 '11 at 16:35













                    • It looks like your script will do what you want. You could include the wget command in the if statement as if ! wget --spider http:///example.com; then.

                      – BillThor
                      Feb 27 '11 at 16:58











                    • you mean wget always return 1 for 200 HTTP response code?

                      – Ashfame
                      Feb 27 '11 at 20:08











                    • I mean the test [ $? != 0 ] is the the same as the test ! command. wget is documented to return 0 on success and not 0 for failure. The if behaves identically which ever way you code it. If wget returns failure on a 200 response, the test will fail either way your write it. The same if it returns 0 for a response code other than 200.

                      – BillThor
                      Feb 27 '11 at 23:25











                    • Thanks! That would make the script smaller and easy to understand.

                      – Ashfame
                      Feb 28 '11 at 5:24














                    5












                    5








                    5







                    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 http://isup.me/example.com 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.






                    share|improve this answer















                    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 http://isup.me/example.com 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.







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Nov 28 '17 at 2:01

























                    answered Feb 27 '11 at 16:20









                    BillThor BillThor

                    4,0511118




                    4,0511118













                    • Thanks for your suggestion! Does my script covers the basic requirement of checking and alerting me when my site is down? And it will be quiet in case there is some Internet connectivity problem

                      – Ashfame
                      Feb 27 '11 at 16:35













                    • It looks like your script will do what you want. You could include the wget command in the if statement as if ! wget --spider http:///example.com; then.

                      – BillThor
                      Feb 27 '11 at 16:58











                    • you mean wget always return 1 for 200 HTTP response code?

                      – Ashfame
                      Feb 27 '11 at 20:08











                    • I mean the test [ $? != 0 ] is the the same as the test ! command. wget is documented to return 0 on success and not 0 for failure. The if behaves identically which ever way you code it. If wget returns failure on a 200 response, the test will fail either way your write it. The same if it returns 0 for a response code other than 200.

                      – BillThor
                      Feb 27 '11 at 23:25











                    • Thanks! That would make the script smaller and easy to understand.

                      – Ashfame
                      Feb 28 '11 at 5:24



















                    • Thanks for your suggestion! Does my script covers the basic requirement of checking and alerting me when my site is down? And it will be quiet in case there is some Internet connectivity problem

                      – Ashfame
                      Feb 27 '11 at 16:35













                    • It looks like your script will do what you want. You could include the wget command in the if statement as if ! wget --spider http:///example.com; then.

                      – BillThor
                      Feb 27 '11 at 16:58











                    • you mean wget always return 1 for 200 HTTP response code?

                      – Ashfame
                      Feb 27 '11 at 20:08











                    • I mean the test [ $? != 0 ] is the the same as the test ! command. wget is documented to return 0 on success and not 0 for failure. The if behaves identically which ever way you code it. If wget returns failure on a 200 response, the test will fail either way your write it. The same if it returns 0 for a response code other than 200.

                      – BillThor
                      Feb 27 '11 at 23:25











                    • Thanks! That would make the script smaller and easy to understand.

                      – Ashfame
                      Feb 28 '11 at 5:24

















                    Thanks for your suggestion! Does my script covers the basic requirement of checking and alerting me when my site is down? And it will be quiet in case there is some Internet connectivity problem

                    – Ashfame
                    Feb 27 '11 at 16:35







                    Thanks for your suggestion! Does my script covers the basic requirement of checking and alerting me when my site is down? And it will be quiet in case there is some Internet connectivity problem

                    – Ashfame
                    Feb 27 '11 at 16:35















                    It looks like your script will do what you want. You could include the wget command in the if statement as if ! wget --spider http:///example.com; then.

                    – BillThor
                    Feb 27 '11 at 16:58





                    It looks like your script will do what you want. You could include the wget command in the if statement as if ! wget --spider http:///example.com; then.

                    – BillThor
                    Feb 27 '11 at 16:58













                    you mean wget always return 1 for 200 HTTP response code?

                    – Ashfame
                    Feb 27 '11 at 20:08





                    you mean wget always return 1 for 200 HTTP response code?

                    – Ashfame
                    Feb 27 '11 at 20:08













                    I mean the test [ $? != 0 ] is the the same as the test ! command. wget is documented to return 0 on success and not 0 for failure. The if behaves identically which ever way you code it. If wget returns failure on a 200 response, the test will fail either way your write it. The same if it returns 0 for a response code other than 200.

                    – BillThor
                    Feb 27 '11 at 23:25





                    I mean the test [ $? != 0 ] is the the same as the test ! command. wget is documented to return 0 on success and not 0 for failure. The if behaves identically which ever way you code it. If wget returns failure on a 200 response, the test will fail either way your write it. The same if it returns 0 for a response code other than 200.

                    – BillThor
                    Feb 27 '11 at 23:25













                    Thanks! That would make the script smaller and easy to understand.

                    – Ashfame
                    Feb 28 '11 at 5:24





                    Thanks! That would make the script smaller and easy to understand.

                    – Ashfame
                    Feb 28 '11 at 5:24











                    3














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



                    alarm.sh



                    #! /bin/bash

                    if curl --silent --head http://www.google.com/ |
                    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.






                    share|improve this answer


























                    • This works perfectly even when the user is behind a captive portal and has not logged in.

                      – Ashhar Hasan
                      May 8 '17 at 13:02











                    • You can use egrep -q instead of egrep ... > /dev/null

                      – wjandrea
                      Nov 28 '17 at 2:26











                    • Why does the script call itself instead of just using a while loop?

                      – wjandrea
                      Nov 28 '17 at 2:26











                    • Oh wait, it doesn't call itself. It calls a script called alarm.sh in the wd, so if you call this script from a different dir, it will either error, or if there's a script called alarm.sh in the wd, it will call that instead. So that's bad practice. You could use "$0" instead, but a while loop would be better.

                      – wjandrea
                      Nov 28 '17 at 2:28













                    • "Why does the script call itself instead of just using a while loop? " : Because I was a noobs when I made that post and yes that script was calling itself.

                      – 01BTC10
                      Dec 1 '17 at 17:19


















                    3














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



                    alarm.sh



                    #! /bin/bash

                    if curl --silent --head http://www.google.com/ |
                    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.






                    share|improve this answer


























                    • This works perfectly even when the user is behind a captive portal and has not logged in.

                      – Ashhar Hasan
                      May 8 '17 at 13:02











                    • You can use egrep -q instead of egrep ... > /dev/null

                      – wjandrea
                      Nov 28 '17 at 2:26











                    • Why does the script call itself instead of just using a while loop?

                      – wjandrea
                      Nov 28 '17 at 2:26











                    • Oh wait, it doesn't call itself. It calls a script called alarm.sh in the wd, so if you call this script from a different dir, it will either error, or if there's a script called alarm.sh in the wd, it will call that instead. So that's bad practice. You could use "$0" instead, but a while loop would be better.

                      – wjandrea
                      Nov 28 '17 at 2:28













                    • "Why does the script call itself instead of just using a while loop? " : Because I was a noobs when I made that post and yes that script was calling itself.

                      – 01BTC10
                      Dec 1 '17 at 17:19
















                    3












                    3








                    3







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



                    alarm.sh



                    #! /bin/bash

                    if curl --silent --head http://www.google.com/ |
                    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.






                    share|improve this answer















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



                    alarm.sh



                    #! /bin/bash

                    if curl --silent --head http://www.google.com/ |
                    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.







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Nov 28 '17 at 2:25









                    wjandrea

                    9,19442363




                    9,19442363










                    answered Apr 20 '12 at 23:34









                    01BTC1001BTC10

                    3762721




                    3762721













                    • This works perfectly even when the user is behind a captive portal and has not logged in.

                      – Ashhar Hasan
                      May 8 '17 at 13:02











                    • You can use egrep -q instead of egrep ... > /dev/null

                      – wjandrea
                      Nov 28 '17 at 2:26











                    • Why does the script call itself instead of just using a while loop?

                      – wjandrea
                      Nov 28 '17 at 2:26











                    • Oh wait, it doesn't call itself. It calls a script called alarm.sh in the wd, so if you call this script from a different dir, it will either error, or if there's a script called alarm.sh in the wd, it will call that instead. So that's bad practice. You could use "$0" instead, but a while loop would be better.

                      – wjandrea
                      Nov 28 '17 at 2:28













                    • "Why does the script call itself instead of just using a while loop? " : Because I was a noobs when I made that post and yes that script was calling itself.

                      – 01BTC10
                      Dec 1 '17 at 17:19





















                    • This works perfectly even when the user is behind a captive portal and has not logged in.

                      – Ashhar Hasan
                      May 8 '17 at 13:02











                    • You can use egrep -q instead of egrep ... > /dev/null

                      – wjandrea
                      Nov 28 '17 at 2:26











                    • Why does the script call itself instead of just using a while loop?

                      – wjandrea
                      Nov 28 '17 at 2:26











                    • Oh wait, it doesn't call itself. It calls a script called alarm.sh in the wd, so if you call this script from a different dir, it will either error, or if there's a script called alarm.sh in the wd, it will call that instead. So that's bad practice. You could use "$0" instead, but a while loop would be better.

                      – wjandrea
                      Nov 28 '17 at 2:28













                    • "Why does the script call itself instead of just using a while loop? " : Because I was a noobs when I made that post and yes that script was calling itself.

                      – 01BTC10
                      Dec 1 '17 at 17:19



















                    This works perfectly even when the user is behind a captive portal and has not logged in.

                    – Ashhar Hasan
                    May 8 '17 at 13:02





                    This works perfectly even when the user is behind a captive portal and has not logged in.

                    – Ashhar Hasan
                    May 8 '17 at 13:02













                    You can use egrep -q instead of egrep ... > /dev/null

                    – wjandrea
                    Nov 28 '17 at 2:26





                    You can use egrep -q instead of egrep ... > /dev/null

                    – wjandrea
                    Nov 28 '17 at 2:26













                    Why does the script call itself instead of just using a while loop?

                    – wjandrea
                    Nov 28 '17 at 2:26





                    Why does the script call itself instead of just using a while loop?

                    – wjandrea
                    Nov 28 '17 at 2:26













                    Oh wait, it doesn't call itself. It calls a script called alarm.sh in the wd, so if you call this script from a different dir, it will either error, or if there's a script called alarm.sh in the wd, it will call that instead. So that's bad practice. You could use "$0" instead, but a while loop would be better.

                    – wjandrea
                    Nov 28 '17 at 2:28







                    Oh wait, it doesn't call itself. It calls a script called alarm.sh in the wd, so if you call this script from a different dir, it will either error, or if there's a script called alarm.sh in the wd, it will call that instead. So that's bad practice. You could use "$0" instead, but a while loop would be better.

                    – wjandrea
                    Nov 28 '17 at 2:28















                    "Why does the script call itself instead of just using a while loop? " : Because I was a noobs when I made that post and yes that script was calling itself.

                    – 01BTC10
                    Dec 1 '17 at 17:19







                    "Why does the script call itself instead of just using a while loop? " : Because I was a noobs when I made that post and yes that script was calling itself.

                    – 01BTC10
                    Dec 1 '17 at 17:19













                    2














                    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.






                    share|improve this answer



















                    • 2





                      nm-tool has been removed in Ubuntu 15.04+, but you can use nmcli instead. E.g. [[ $(nmcli -f STATE -t g) = connected ]]

                      – Six
                      Jan 27 '16 at 15:15











                    • @Six nmcli -f STATE -t nm the good thing is being independent of web sites!

                      – Aquarius Power
                      Jan 31 '16 at 2:13













                    • Note that nm-tool and nmcli will tell you only whether or not you're connected to local network, i.e. whether or not you're connected to your home wifi/ethernet. It won't tell you whether or not you can reach anything beyond your local network, i.e. internet.

                      – Sergiy Kolodyazhnyy
                      Nov 28 '17 at 3:27
















                    2














                    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.






                    share|improve this answer



















                    • 2





                      nm-tool has been removed in Ubuntu 15.04+, but you can use nmcli instead. E.g. [[ $(nmcli -f STATE -t g) = connected ]]

                      – Six
                      Jan 27 '16 at 15:15











                    • @Six nmcli -f STATE -t nm the good thing is being independent of web sites!

                      – Aquarius Power
                      Jan 31 '16 at 2:13













                    • Note that nm-tool and nmcli will tell you only whether or not you're connected to local network, i.e. whether or not you're connected to your home wifi/ethernet. It won't tell you whether or not you can reach anything beyond your local network, i.e. internet.

                      – Sergiy Kolodyazhnyy
                      Nov 28 '17 at 3:27














                    2












                    2








                    2







                    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.






                    share|improve this answer













                    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.







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 19 '12 at 0:46









                    Venkat KotraVenkat Kotra

                    3492412




                    3492412








                    • 2





                      nm-tool has been removed in Ubuntu 15.04+, but you can use nmcli instead. E.g. [[ $(nmcli -f STATE -t g) = connected ]]

                      – Six
                      Jan 27 '16 at 15:15











                    • @Six nmcli -f STATE -t nm the good thing is being independent of web sites!

                      – Aquarius Power
                      Jan 31 '16 at 2:13













                    • Note that nm-tool and nmcli will tell you only whether or not you're connected to local network, i.e. whether or not you're connected to your home wifi/ethernet. It won't tell you whether or not you can reach anything beyond your local network, i.e. internet.

                      – Sergiy Kolodyazhnyy
                      Nov 28 '17 at 3:27














                    • 2





                      nm-tool has been removed in Ubuntu 15.04+, but you can use nmcli instead. E.g. [[ $(nmcli -f STATE -t g) = connected ]]

                      – Six
                      Jan 27 '16 at 15:15











                    • @Six nmcli -f STATE -t nm the good thing is being independent of web sites!

                      – Aquarius Power
                      Jan 31 '16 at 2:13













                    • Note that nm-tool and nmcli will tell you only whether or not you're connected to local network, i.e. whether or not you're connected to your home wifi/ethernet. It won't tell you whether or not you can reach anything beyond your local network, i.e. internet.

                      – Sergiy Kolodyazhnyy
                      Nov 28 '17 at 3:27








                    2




                    2





                    nm-tool has been removed in Ubuntu 15.04+, but you can use nmcli instead. E.g. [[ $(nmcli -f STATE -t g) = connected ]]

                    – Six
                    Jan 27 '16 at 15:15





                    nm-tool has been removed in Ubuntu 15.04+, but you can use nmcli instead. E.g. [[ $(nmcli -f STATE -t g) = connected ]]

                    – Six
                    Jan 27 '16 at 15:15













                    @Six nmcli -f STATE -t nm the good thing is being independent of web sites!

                    – Aquarius Power
                    Jan 31 '16 at 2:13







                    @Six nmcli -f STATE -t nm the good thing is being independent of web sites!

                    – Aquarius Power
                    Jan 31 '16 at 2:13















                    Note that nm-tool and nmcli will tell you only whether or not you're connected to local network, i.e. whether or not you're connected to your home wifi/ethernet. It won't tell you whether or not you can reach anything beyond your local network, i.e. internet.

                    – Sergiy Kolodyazhnyy
                    Nov 28 '17 at 3:27





                    Note that nm-tool and nmcli will tell you only whether or not you're connected to local network, i.e. whether or not you're connected to your home wifi/ethernet. It won't tell you whether or not you can reach anything beyond your local network, i.e. internet.

                    – Sergiy Kolodyazhnyy
                    Nov 28 '17 at 3:27











                    1














                    I am using this method:



                    if curl -s --head  --request GET www.google.com | 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.






                    share|improve this answer




























                      1














                      I am using this method:



                      if curl -s --head  --request GET www.google.com | 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.






                      share|improve this answer


























                        1












                        1








                        1







                        I am using this method:



                        if curl -s --head  --request GET www.google.com | 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.






                        share|improve this answer













                        I am using this method:



                        if curl -s --head  --request GET www.google.com | 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.







                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Jan 28 at 7:12









                        Carlos AbrahamCarlos Abraham

                        1113




                        1113























                            0














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



                            echo $(nm-online) $? connection problems





                            share|improve this answer
























                            • how does this work?

                              – wjandrea
                              Nov 28 '17 at 2:31











                            • It is just checking the status (one character) of the nm-online command... It will return 0 if everything is fine. Usual in all UNIX shells.

                              – Antonio
                              Mar 3 '18 at 23:16


















                            0














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



                            echo $(nm-online) $? connection problems





                            share|improve this answer
























                            • how does this work?

                              – wjandrea
                              Nov 28 '17 at 2:31











                            • It is just checking the status (one character) of the nm-online command... It will return 0 if everything is fine. Usual in all UNIX shells.

                              – Antonio
                              Mar 3 '18 at 23:16
















                            0












                            0








                            0







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



                            echo $(nm-online) $? connection problems





                            share|improve this answer













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



                            echo $(nm-online) $? connection problems






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Apr 23 '14 at 7:21









                            octius4uoctius4u

                            11




                            11













                            • how does this work?

                              – wjandrea
                              Nov 28 '17 at 2:31











                            • It is just checking the status (one character) of the nm-online command... It will return 0 if everything is fine. Usual in all UNIX shells.

                              – Antonio
                              Mar 3 '18 at 23:16





















                            • how does this work?

                              – wjandrea
                              Nov 28 '17 at 2:31











                            • It is just checking the status (one character) of the nm-online command... It will return 0 if everything is fine. Usual in all UNIX shells.

                              – Antonio
                              Mar 3 '18 at 23:16



















                            how does this work?

                            – wjandrea
                            Nov 28 '17 at 2:31





                            how does this work?

                            – wjandrea
                            Nov 28 '17 at 2:31













                            It is just checking the status (one character) of the nm-online command... It will return 0 if everything is fine. Usual in all UNIX shells.

                            – Antonio
                            Mar 3 '18 at 23:16







                            It is just checking the status (one character) of the nm-online command... It will return 0 if everything is fine. Usual in all UNIX shells.

                            – Antonio
                            Mar 3 '18 at 23:16













                            0














                            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="http://www.google.com"
                            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;





                            share|improve this answer






























                              0














                              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="http://www.google.com"
                              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;





                              share|improve this answer




























                                0












                                0








                                0







                                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="http://www.google.com"
                                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;





                                share|improve this answer















                                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="http://www.google.com"
                                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;






                                share|improve this answer














                                share|improve this answer



                                share|improve this answer








                                edited Nov 18 '14 at 14:13

























                                answered Nov 18 '14 at 13:31









                                pabloabpabloab

                                474




                                474























                                    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" your_email@gmail.com

                                      #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" your_email@gmail.com
                                      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







                                    share|improve this answer






























                                      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" your_email@gmail.com

                                        #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" your_email@gmail.com
                                        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







                                      share|improve this answer




























                                        0












                                        0








                                        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" your_email@gmail.com

                                          #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" your_email@gmail.com
                                          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







                                        share|improve this answer















                                        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" your_email@gmail.com

                                          #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" your_email@gmail.com
                                          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








                                        share|improve this answer














                                        share|improve this answer



                                        share|improve this answer








                                        edited Jul 14 '15 at 13:56









                                        Community

                                        1




                                        1










                                        answered May 8 '14 at 0:00









                                        RafaelRafael

                                        11




                                        11























                                            0














                                            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
                                            # https://askubuntu.com/questions/27954/how-can-i-check-internet-connectivity-in-a-console
                                            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





                                            share|improve this answer




























                                              0














                                              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
                                              # https://askubuntu.com/questions/27954/how-can-i-check-internet-connectivity-in-a-console
                                              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





                                              share|improve this answer


























                                                0












                                                0








                                                0







                                                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
                                                # https://askubuntu.com/questions/27954/how-can-i-check-internet-connectivity-in-a-console
                                                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





                                                share|improve this answer













                                                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
                                                # https://askubuntu.com/questions/27954/how-can-i-check-internet-connectivity-in-a-console
                                                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






                                                share|improve this answer












                                                share|improve this answer



                                                share|improve this answer










                                                answered Mar 3 '18 at 23:11









                                                AntonioAntonio

                                                81121117




                                                81121117






























                                                    draft saved

                                                    draft discarded




















































                                                    Thanks for contributing an answer to Ask Ubuntu!


                                                    • Please be sure to answer the question. Provide details and share your research!

                                                    But avoid



                                                    • Asking for help, clarification, or responding to other answers.

                                                    • Making statements based on opinion; back them up with references or personal experience.


                                                    To learn more, see our tips on writing great answers.




                                                    draft saved


                                                    draft discarded














                                                    StackExchange.ready(
                                                    function () {
                                                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2faskubuntu.com%2fquestions%2f27954%2fhow-can-i-check-internet-connectivity-in-a-console%23new-answer', 'question_page');
                                                    }
                                                    );

                                                    Post as a guest















                                                    Required, but never shown





















































                                                    Required, but never shown














                                                    Required, but never shown












                                                    Required, but never shown







                                                    Required, but never shown

































                                                    Required, but never shown














                                                    Required, but never shown












                                                    Required, but never shown







                                                    Required, but never shown







                                                    Popular posts from this blog

                                                    How to make a Squid Proxy server?

                                                    Is this a new Fibonacci Identity?

                                                    19世紀