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

One thought on “Test TCP connection without telnet or nc

  1. Permalink  ⋅ Reply

    Dicky Dwijanto

    November 6, 2017 at 9:27am

    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…

Leave a Reply

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