In my diary activities usually I have to check the connectivity between two hosts. In this article I will explain which is the method I use to do it.

What is Netcat?

Netcat (often abbreviated to nc) is a tool able to establish TCP connection between two hosts, also used for reading or writing to the network connections. As it has many features, it is often used as a network debugging and investigation tool.

Commands to check connections

Basic TCP connection check

The most basic command is to use netcat (nc) to establish a TCP connection. The info it needs is the IP address or domain and the TCP Port.

root|lavrea:~$ nc 64.13.192.208 25
220 cl03.gs01.gridserver.com ESMTP Exim 4.94.2 Wed, 20 Jul 2022 13:07:50 -0700
^C
root|lavrea:~$ 

Here you see the answer of the other host, and the connection is established until you close with a Ctrl+C or a timeout expires.

Advanced TCP connection check

This is a more advanced method, in which it is added some parameters to the command.

  • -w is used to establish the time (in seconds) to wait a connection.
  • -v is used to give verbose information.
  • -z is used to only scan open ports, without sending any data to them.

The format should be like this:

nc -w 1 -vz <HOST OR IP> <TCP PORT>

This is my favorite command to check TCP connections. Here you have an example of a successful connection:

root|lavrea:~$ nc -w 1 -vz 64.13.192.208 25
Connection to 64.13.192.208 25 port [tcp/smtp] succeeded!
root|lavrea:~$

An example of a failed connection:

root|lavrea:~$ nc -w 1 -vz ophelia.ga 5000
nc: connect to ophelia.ga port 5000 (tcp) failed: Connection refused
root|lavrea:~$

So with this tool, it is easy to check whether a TCP connection is working or not.

TCP port scanning

If you need to check several ports of a host, there is an option to check a list of ports, which makes life easier.

nc -w 1 -vz <HOST OR IP> <FIRST PORT>-<LAST PORT>

An example to check TCP ports between 20 and 25:

root|lavrea:~$ nc -w 1 -vz ophelia.ga 20-25
nc: connect to ophelia.ga port 20 (tcp) failed: Connection refused
nc: connect to ophelia.ga port 21 (tcp) failed: Connection refused
Connection to ophelia.ga 22 port [tcp/ssh] succeeded!
nc: connect to ophelia.ga port 23 (tcp) failed: Connection refused
nc: connect to ophelia.ga port 24 (tcp) failed: Connection refused
Connection to ophelia.ga 25 port [tcp/smtp] succeeded!
root|lavrea:~$ 

You could also check a list of non-consecutive ports:

root|lavrea:~$ nc -w 1 -vz ophelia.ga 20 22 550 3212
nc: connect to ophelia.ga port 20 (tcp) failed: Connection refused
Connection to ophelia.ga 22 port [tcp/ssh] succeeded!
nc: connect to ophelia.ga port 550 (tcp) failed: Connection refused
nc: connect to ophelia.ga port 3212 (tcp) failed: Connection refused
root|lavrea:~$

Conclusion

Netcat is a powerful tool which could be useful for debugging connectivity issues. Maybe in a later post I will explain how to use for other purposes.