Testing a TCP connection using bash

2 min read | by Jordi Prats

To be able to debug issues we can test a TCP connection using netcat (nc) or even telnet. But when we are on a containerized environment such as Kubernetes it can be a challenge when the container doesn't have the right tools for the job

$ nc
bash: nc: command not found
$ netcat
bash: netcat: command not found
$ telnet
bash: telnet: command not found

But we can also test a TCP connection using just bash. To do so we can use /dev/tcp// as follows:

timeout 1 bash -c 'cat < /dev/null > /dev/tcp/'; echo $?

So, if it can connect successfully it will just return 0:

$ timeout 1 bash -c 'cat < /dev/null > /dev/tcp/google.com/80'; echo $?

Otherwise we'll get an error message:

$ timeout 1 bash -c 'cat < /dev/null > /dev/tcp/'; echo $?
bash: connect: Connection refused
bash: /dev/tcp/ Connection refused

Posted on 05/07/2021