Test TCP connection without telnet or nc

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
Connected to www.google.com.
Escape character is '^]'.


$ 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 $?

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

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 $?

Leave a Reply

Your email will not be published. Name and Email fields are required.