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 ncThe basic netcat command follows this syntax:
netcat [options] host portThis 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 172.16.0.33 80 Connection to 172.16.0.33 80 port [tcp/http] succeeded! [roo@vs12app001:~]#You will notice that used options -vz which are defined below:
-vHave nc give more verbose output.
-zSpecifies that nc should just scan for listening daemons, withoutsending 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 172.16.0.33 80 nc: connect to 172.16.0.33 port 80 (tcp) failed: Connection timed out [roo@vs12app001:~]#If the port was open but a firewall blocked it then you would see a connection refused error:
[roo@vs12app001:~]# nc -vz 172.16.0.33 80 nc: connect to 172.16.0.33 port 80 (tcp) failed: Connection refused [roo@vs12app001:~]#To test connectivity over a range of ports use the following syntax:
netcat host startport-endportThe command below shows this in practice, where I test connectivity to 172.16.0.31 on port rage 8080-8085:
[roo@vs12app001:~]# nc -vz 172.16.0.33 8080-8085 Connection to 172.16.0.33 8080 port [tcp/http-alt] succeeded! Connection to 172.16.0.33 8081 port [tcp/tproxy] succeeded! nc: connect to 172.16.0.33 port 8082 (tcp) failed: Connection refused nc: connect to 172.16.0.33 port 8083 (tcp) failed: Connection refused nc: connect to 172.16.0.33 port 8084 (tcp) failed: Connection refused nc: connect to 172.16.0.33 port 8085 (tcp) failed: Connection refused [roo@vs12app001:~]#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.
References:
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