How to check if internet connection is available via Terminal
6,752
Solution 1
Try using the curl
command and checking the exit status in an if
statement.
curl -D- -o /dev/null -s http://www.google.com
if [[ $? == 0 ]]; then
foocode
else
exit 1
fi
Solution 2
I was using snmp when I had a router that support it to get the ip assigned to the Wan interface (.253 was the router addr):
IP=$(/usr/bin/snmpwalk -v2c -Ov -cpublic 192.168.1.253 \
IP-MIB::ipAdEntAddr 2>/dev/null \
| /bin/grep -v "0.0.0.0\|127.0.0.1\|192.168.1.253")
Or maybe you could webscarp it from the router's stat pages with curl.
Currently instead I use to check/get the ip from the service I use for the dynamic dns:
IP=$(curl -s 'http://checkip.dyndns.org' | sed 's/.*Current IP Address: \([0-9\.]*\).*/\1/g')
and then:
if [ "$IP" != "" ] && [ "$IP" != "0.0.0.0" ]; then
# connected
Related videos on Youtube
Author by
Niresh
Updated on September 18, 2022Comments
-
Niresh over 1 year
I'm trying to write a Bash script that is aware of internet connectivity.
How can I achieve that?
For example:
if (something that checks internet connection);then curl -o new someurl else exit 1