Sometimes you need to test if a network connection works without actually using the intended client program. Normally you would use a tool like telnet or nc to do this, e.g.
$ telnet www.google.com 80 Trying 172.217.20.68... Connected to www.google.com. Escape character is '^]'.
or
$ nc -z -v -w5 www.google.com 80 Connection to www.google.com 80 port [tcp/http] succeeded!
But these tools aren’t always installed on the machine you want to test the connection from. You can then use bash to check the connection.
$ timeout 5 bash -c 'cat < /dev/null > /dev/tcp/www.google.com/80'; echo $? 0
If the result is 0, the connection was successful. If there is an error before the timeout is hit, e.g. the hostname is not known, the result is 1:
$ timeout 5 bash -c 'cat < /dev/null > /dev/tcp/www.google.not_a_tld/80'; echo $? bash: www.google.not_a_tld: Name or service not known bash: /dev/tcp/www.google.not_a_tld/80: Invalid argument 1
If there is a timeout, e.g. the network refuses to set up the connection or there is no process listening on the specified host and port, the result is 124:
$ timeout 5 bash -c 'cat < /dev/null > /dev/tcp/www.google.not_a_tld/80'; echo $? 124
Test TCP connection without telnet or nc
Very useful tips, I think it’s common situation that we need to check local or remote host/port in minimal Linux environment without authority to install additional components, I’ve checked it on Centos 7 minimal installation and openSUSE Leap 42.1 and it works well. Thanks for the tips…
Can you explain this command:
timeout 5 bash -c ‘cat /dev/tcp/www.google.com/80’; echo $?
I am interested more in understanding what is going on in this part of the command:
bash -c ‘cat /dev/tcp/www.google.com/80’
Best. Linux. Tip. Ever.
I do not have /dev/tcp on my server. Any other way ?
cvvr, /dev/tcp isn’t a file that you can find in the filesystem; according to bash(1), bash itself is what recognizes the “/dev/tcp/[ip]/[port]” ‘path’ and decides to make a TCP connection to it.
I am using this command remotely by passing bunch of server list in a input file.. For some servers it is responding with “0” and for some servers with “1”.. Invalid argument error……… I am converting hostname to ip and storing it in tempory file from which the ip is taken for the /dev/tcp command…..
Please suggest anything needed
This is fricken awesome. In a production env, we never have telnet or netcat available and its too much of a hassle to get netcat installed. This works beautifully. Much thanks!
This works beautifully. big thanks!
I think do not have /dev/tcp on my server. Any other way ?