Skip to content
Advertisement

How to programmatically check for connection?

In Linux (Ubuntu), I want to programmatically check if there is Internet connection (or if eth0 is connected).

I’m doing this because I am writing a program that requires network connection on a system that is highly prone to lose connection.

So I was thinking maybe a script that I can run periodically to check.

Can you give me good suggestions?

Advertisement

Answer

Here is a quick script that will accomplish what you want:

EMAIL=youremail@something.com
ping -c 5 8.8.8.8 >> /dev/null

if [ $? -eq  0 ]
    then
    echo "Able to reach internet!" | mail $EMAIL
else
    echo "Unable to reach internet!" | mail $EMAIL
fi

Obviosly you can change the mail to something else to do depending on what your goal is EDIT: to explain, this pings googles dns server to ensure you are connected and sends you an email one way or the other. The email part on failure will only work of course if you have a local email server on your network.

Advertisement