Testing connectivity using netcat on RHEL/CentOS

In this post I am going to show you how to test connectivity to a server on specific ports, essentially port scanning. We will perform these tests using a tool called netcat, which is a versatile networking utility for debugging and investigating the network.

Although the title states that this is for RHEL/CentOS, the same syntax applies for Ubuntu as I have tested it. I am sure it works for other versions of Linux, I just haven’t tested them so cannot confirm.

Before using netct, you must install it. On RHEL/CentOS, install it using yum:

yum install nc

The basic netcat command follows this syntax:

netcat [options] host port

This command will initiate a TCP connaction to the host and port stated in the command. Please note that netcat always initiates a TCP connection by default unless you specifically use the -u option which specifies UDP. Another thing to note is that connections made via netcat are unencrypted.

So using the above, I can test whether a web server is listening on port 80 by running the following command:

[roo@vs12app001:~]# nc -vz 80
Connection to 80 port [tcp/http] succeeded!

You will notice that used options -vz which are defined below:

-v Have nc give more verbose output.
-z Specifies that nc should just scan for listening daemons, without sending any data to them.

If the connection failed, meaning that port 80 is not open then you would see a time out error per the below:

[roo@vs12app001:~]# nc -vz 80
nc: connect to port 80 (tcp) failed: Connection timed out

If the port was open but a firewall blocked it then you would see a connection refused error:

[roo@vs12app001:~]# nc -vz 80
nc: connect to port 80 (tcp) failed: Connection refused

To test connectivity over a range of ports use the following syntax:

netcat host startport-endport

The command below shows this in practice, where I test connectivity to on port rage 8080-8085:

[roo@vs12app001:~]# nc -vz 8080-8085
Connection to 8080 port [tcp/http-alt] succeeded!
Connection to 8081 port [tcp/tproxy] succeeded!
nc: connect to port 8082 (tcp) failed: Connection refused
nc: connect to port 8083 (tcp) failed: Connection refused
nc: connect to port 8084 (tcp) failed: Connection refused
nc: connect to port 8085 (tcp) failed: Connection refused

There are many more examples of how netcat can be used but the ones above are how I utilize this tool the most. See the references below for more information.

Testing Network Services with netcat
How To Use Netcat to Establish and Test TCP and UDP Connections on a VPS
8 Practical Linux Netcat NC Command Examples
Linux Command Man Page for netcat