Linux - How to test if a TCP Port is open
Ubuntu
I enjoy troubleshooting network connections. Typically when I design and deploy applications and systems I try to ensure that the network is set up correctly first, rather than an afterthought.
I have found that networking is often an afterthought at most companies I have worked for. In a perfect world, after a VM is created, you should run a TCP/UDP Port Listener Utility like the one I made for Windows and test the network design. Testing and creating ports on Linux is a bit easier as it has a Netcat command.
Netcat command
The netcat command can both create a listener, as well as test that the port is open.
Netcat TCP Listener
I always forget that the Netcat command (nc) can be used as a listener. This is due to the listener option missing in the help output. Here is what the help info says. I have also told the machine to start listening on port 8081 using the command below:
nc -l 8081Now that you run that command the machine will listen on that port. Once it been tested once, the command will exit. If you want to test port 8081 twice, you need to run the port listener command before each test.
Ports in use
When you are creating a listener you might get a “Permission Denied”. You might think this is due to not running the command using “sudo” but you would be wrong.
When you see “Permission Denied” it means there is already another service running on that port. This is another great way to test if a port is running on the machine. Imagine installing an application and wondering why it isn’t communicating just to find out that the port is already being listened on by another app you may or may not be aware of.
Netcat TCP Port Test
Now that the port is running from the previous section I will open a different terminal to test. To test that port 8081 is being listened on you can run this command:
nc -v -w 2 localhost 8081In the screenshot below you can see it worked the first time. If I run the command right after the first one you can see it fails on the second try. As stated, this is to be expected unless you restart the listener.
By using Port Listeners and Testers you can essentially pre-test all the networking to make sure that there are no firewall issues between the machines. This testing works best BEFORE you start installing the rest of the software or configuring services.
Tests like this take very little time and can drastically reduce frustrations in the deployment of systems or applications.





