How to test an Internet connection with bash?
How can an internet connection be tested without pinging some website? I mean, what if there is a connection but the site is down? Is there a check for a connection with the world?
There is no better way than sending and receiving a single packet to a set of addresses that you know not to go offline all at once, another way is to check your current set DNS if you don’t want your application to ping a more public domain.
22 Answers 22
Without ping
#!/bin/bash wget -q --spider http://google.com if [ $? -eq 0 ]; then echo "Online" else echo "Offline" fi
-q : Silence mode
—spider : don’t get, just check page availability
$? : shell return code
0 : shell «All OK» code
Without wget
#!/bin/bash echo -e "GET http://google.com HTTP/1.0\n\n" | nc google.com 80 > /dev/null 2>&1 if [ $? -eq 0 ]; then echo "Online" else echo "Offline" fi
@user3439968 You need to add timeout to nc to make sure it times out. something like nc google.com 80 -w 10
Ping your default gateway:
#!/bin/bash ping -q -w 1 -c 1 `ip r | grep default | cut -d ' ' -f 3` > /dev/null && echo ok || echo error
good technique, it can be modified to be used in a function: function ping_gw() < . && return 0 || return 1 >and then used like so: ping_gw || (echo «no network, bye» && exit 1)
on mac os this does not work via copy-paste: «-bash: ip: command not found ping: illegal option — w»
Be careful with this. I just tested this by doing ifconfig down wlan0 and I still have a default gateway and it is pingable, even though I in fact cannot reach the outside world.
Super Thanks to user somedrew for their post here: https://bbs.archlinux.org/viewtopic.php?id=55485 on 2008-09-20 02:09:48
Looking in /sys/class/net should be one way
Here’s my script to test for a network connection other than the loop back. I use the below in another script that I have for periodically testing if my website is accessible. If it’s NOT accessible a popup window alerts me to a problem.
The script below prevents me from receiving popup messages every five minutes whenever my laptop is not connected to the network.
#!/usr/bin/bash # Test for network conection for interface in $(ls /sys/class/net/ | grep -v lo); do if [[ $(cat /sys/class/net/$interface/carrier) = 1 ]]; then OnLine=1; fi done if ! [ $OnLine ]; then echo "Not Online" > /dev/stderr; exit; fi
Note for those new to bash: The final ‘if’ statement tests if NOT [!] online and exits if this is the case. See man bash and search for «Expressions may be combined» for more details.
P.S. I feel ping is not the best thing to use here because it aims to test a connection to a particular host NOT test if there is a connection to a network of any sort.
P.P.S. The Above works on Ubuntu 12.04 The /sys may not exist on some other distros. See below:
Method to check connectivity to other server
I want to check connectivity between 2 servers (i.e. if ssh will succeed). The main idea is to check the shortest way between server-a and server-b using a list of middle servers (for example if I’m on dev server and I want to connect to prod server — usually a direct ssh will fail). Because this can take a while, I prefer not to use SSH — rather I prefer to check first if I can connect and if so then try to connect through SSH. Some possible routes to get the idea:
server-a -> server-b server-a -> middle-server-1 -> server-b server-a -> middle-server-6 -> server-b server-a -> middle-server-3 -> middle-server-2 -> server-b
3 Answers 3
For checking server connectivity you have 4 tools at your disposal.
- ping This will check to see if any of the servers you’re attempting to connect through, but won’t be able to see if middle-server-1 can reach server-b, for example. You can gate how long ping will attempt to ping another server through the use of the count switch ( -c ). Limiting it to 1 should suffice.
$ ping -c 1 skinner PING skinner (192.168.1.3) 56(84) bytes of data. 64 bytes from skinner (192.168.1.3): icmp_req=1 ttl=64 time=5.94 ms --- skinner ping statistics --- 1 packets transmitted, 1 received, 0% packet loss, time 0ms rtt min/avg/max/mdev = 5.946/5.946/5.946/0.000 ms
You can check the status of this command through the use of this variable, $? . If it has the value 0 then it was successful, anything else and a problem occurred.
$ traceroute skinner traceroute to skinner (192.168.1.3), 30 hops max, 60 byte packets 1 skinner (192.168.1.3) 0.867 ms 0.859 ms 0.929 ms
$ ssh -o "BatchMode=yes" skinner
$ ssh -q -o "BatchMode=yes" skinner "echo 2>&1" && echo $host SSH_OK || echo $host SSH_NOK SSH_OK
If it works you’ll get a SSH_OK message, if it fails you’ll get a SSH_NOK message. An alternative to this method is to also include the ConnectTimeout option. This will guard the ssh client from taking a long time. Something like this typically is acceptable, ConnectTimeout=5 . For example:
$ ssh -o BatchMode=yes -o ConnectTimeout=5 skinner echo ok 2>&1 ok
$ ssh -o BatchMode=yes -o ConnectTimeout=5 mungr echo ok 2>&1 ssh: connect to host 192.168.1.2 port 22: No route to host
$ echo quit | telnet skinner 22 2>/dev/null | grep Connected Connected to skinner.
6 Linux Utility to Test Network Connectivity
Invicti Web Application Security Scanner – the only solution that delivers automatic verification of vulnerabilities with Proof-Based Scanning™.
Wondering how to check connectivity between two network endpoints?
One of the common tasks for sysadmin is to check the connectivity to troubleshoot networking issues. It could be anything like application can’t connect to backend service, unable to fetch data from external URL, verify if the flow is opened, etc.
Whatever it might be, the following utility/commands would help you. They are tested on CentOS, and I don’t see any reason not to work on another Linux distro.
telnet
One of the widely used commands to test essential connectivity between servers, server to another network device’s IP. The syntax for the command is easy.
telnet $destinationIP $PORT
Let’s say you want to test if you can connect to port 8080 on 10.0.0.1 IP address; then the command would be.
If there is no issue in connecting, then you should see the connected message.
Trying 10.0.0.1. Connected to 10.0.0.1. Escape character is '^]'.
Note: if you get a command not found while executing telnet then you need to install telnet as I explained here.
In most of the scenarios, telnet should help. However, if you need some other option then here are some telnet alternatives.
ncat or nc
Ncat (a.k.a. nc) is a powerful network utility with many features like bind and accept a connection, execute commands remotely, write and read data, etc. It works on IPv4 and IPv6, both.
To do a simple test to check if the port is opened or not, you will execute the following.
Let’s take an example of testing 443 port on geekflare.com.
[root@geekflare-lab ~]# nc -vz geekflare.com 443 Ncat: Version 7.50 ( https://nmap.org/ncat ) Ncat: Connected to 104.25.133.107:443. Ncat: 0 bytes sent, 0 bytes received in 0.02 seconds. [root@geekflare-lab ~]#
As mentioned, you can also use nc to bind the connection to listen on a particular port. This can be handy when you don’t have actual services running but want to ensure connectivity exists.
To start listening on a port:
It will bind the port to a given number.
If ncat is not installed, then you can get it done with yum install nc on CentOS/RHEL servers.
wget
wget is a useful command to download/test HTTP, HTTPS, and FTP. If you are working as a web engineer or often dealing with web-related issues then wget is your friend. Testing using wget is straightforward.
Here is an example of testing tools.geekflare.com
[root@geekflare-lab ~]# wget tools.geekflare.com --2019-05-09 20:40:01-- http://tools.geekflare.com/ Resolving tools.geekflare.com (tools.geekflare.com). 104.25.134.107, 104.25.133.107, 2606:4700:20::6819:866b, . Connecting to tools.geekflare.com (tools.geekflare.com)|104.25.134.107|:80. connected. HTTP request sent, awaiting response. 301 Moved Permanently Location: https://tools.geekflare.com/ [following] --2019-05-09 20:40:01-- https://tools.geekflare.com/ Connecting to tools.geekflare.com (tools.geekflare.com)|104.25.134.107|:443. connected. HTTP request sent, awaiting response. 200 OK Length: unspecified [text/html] Saving to: 'index.html.2' [ ] 15,139 --.-K/s in 0.001s 2019-05-09 20:40:02 (12.8 MB/s) - 'index.html.2' saved [15139] [root@geekflare-lab ~]#
If it shows connected means there is no connectivity issue.
Check out this to see some of the frequently used wget command examples.
curl
A curl is a multipurpose tool.
Do you know you can telnet to a port using curl?
The following is a working example.
[root@geekflare-lab ~]# curl -v telnet://chandan.io:443 * About to connect() to chandan.io port 443 (#0) * Trying 104.31.68.106. * Connected to chandan.io (104.31.68.106) port 443 (#0)
And, when there is no listening port or firewall issue, then you will see trying…
[root@geekflare-lab ~]# curl -v telnet://chandan.io:4434 * About to connect() to chandan.io port 4434 (#0) * Trying 104.31.68.106.
You can also use curl to download the data. It supports multiple protocols – HTTP, HTTPS, FTP, IMAP, LDAP, POP3, SCP, SFTP, GOPHER, etc.
nmap
A popular tool with hundreds of features. Often this is considered as a security tool, nmap lets you test a single IP/port or in the range.
An example of testing port 443 on siterelic.com
[root@geekflare-lab ~]# nmap -p 443 siterelic.com Starting Nmap 7.70 ( https://nmap.org ) at 2019-05-10 06:55 UTC Nmap scan report for siterelic.com (104.27.174.50) Host is up (0.0079s latency). Other addresses for siterelic.com (not scanned): 104.27.175.50 2606:4700:30::681b:ae32 2606:4700:30::681b:af32 PORT STATE SERVICE 443/tcp open https Nmap done: 1 IP address (1 host up) scanned in 0.13 seconds [root@geekflare-lab ~]#
Look at the state column. If you see open means connection is ok. And, if the state is filtered that means connectivity doesn’t exist.
Ping
One of the widely used commands is to check if a remote host is responding to ICMP ECHO_REQUEST or not. Keep in mind, this may not give you accurate results when ICMP is blocked at the remote network’s firewall. Assuming that’s not the case, you can ping to IPv4 or IPv4 network endpoint as below.
For example, success result of geekflare.com
chandan@192 ~ % ping geekflare.com PING geekflare.com (104.27.119.115): 56 data bytes 64 bytes from 104.27.119.115: icmp_seq=0 ttl=53 time=7.944 ms 64 bytes from 104.27.119.115: icmp_seq=1 ttl=53 time=8.870 ms
For example, failure result of internal IP.
chandan@192 ~ % ping 192.168.0.1 PING 192.168.0.1 (192.168.0.1): 56 data bytes Request timeout for icmp_seq 0 Request timeout for icmp_seq 1
If the endpoint supports IPv6, you can use the ping6 command as below.
chandan@192 ~ % ping6 geekflare.com PING6(56=40+8+8 bytes) 2a01:4b00:88e4:8700:d8ca:bf50:159c:2a1d --> 2606:4700:20::681b:7673 16 bytes from 2606:4700:20::681b:7673, icmp_seq=0 hlim=250 time=8.650 ms 16 bytes from 2606:4700:20::681b:7673, icmp_seq=1 hlim=250 time=8.738 ms
If you need to do remote ping over the Internet, you can use the online ping tool.
Conclusion
telnet is phasing out in the latest Linux version. Thanks to the above telnet alternative.
If you are new to Linux and looking to learn then check out this Udemy course.