Verifying which all ports are open and listening on the network interfaces of a server is very important when it comes to server security as well as troubleshooting service-related issues.
Vulnerable open ports can be the cause of severe security breach in a server. It is a must that such ports are found out and closed/disabled.
In case of service-related issues, checking which all ports are in use can be used a troubleshooting mechanism to find if multiple services are listening on the same port.
This guide outlines the basic steps to determine which all ports are open in a service using commands such as
nmap in Linux server and
netstat in Windows server.
An example for this, is when both Apache and Nginx services run in the same server.
Method 1 - Using
lsof (list open files) is a command that is used to display the list of all open files in a server and the services that has opened them.
The general syntax of the
lsof command is as below:
# sudo lsof -i -P -n
grep command, the result of the above command can be filtered to show the result of files that are listening on different ports in the server.
# sudo lsof -i -P -n | grep LISTEN # doas lsof -i -P -n | grep LISTEN (for OpenBSD systems)
Taking the last line from sample output, the result can be explained as below:
named 812 named 23u IPv4 16018 0t0 TCP 220.127.116.11:53 (LISTEN)
Method 2 - Using
netstat (network statistics) is a command line tool that can be used to monitor both incoming and outgoing network connections in a server.
netstat command along with the grep command to check the listening services can be used in the below syntax
# netstat -tulpn | grep LISTEN # netstat -nat | grep LISTEN (for OpenBSD systems)
netstat command has been deprecated in the latest versions of Linux distribution. The
ss command has taken its place.
The syntax for using the
ss command is as provided below:
# sudo ss -tulpn
The switches for the
ss command mean as follows:
Method 3 - Using
nmap (network mapper) is a network scanner command tool that can be used to find out hosts and services on a server. This is done by sending packets to the server and analyzing the results further.
The general syntax of the
nmap command that can be executed from within the server is as follows:
# sudo nmap -sT -O localhost # sudo nmap -sTU -O 18.104.22.168 (scan both TCP and UDP for server)
In Windows servers, the
netstat command can be used to check the ports that are currently in use in the server.
The syntax for the
wnetstat command to be used in Windows servers is as below:
> netstat -bano | more > netstat -bano | findstr /R /C:"[LISTENING]"
Each field in above result mean as below: