Check if port is open or closed on a Linux server?

netstat -an | grep PORTNUMBER | grep -i listen

If the output is empty, the port is not in use.

nc -w5 -z -v <ip_address> <port_number>, you should get something like Connection to 127.0.0.1 9000 port [tcp/*] succeeded!, otherwise port is closed
# iptables -L -n | grep 5666
ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0            tcp dpt:5666
# netstat -an | grep 5666 | grep -i listen
tcp        0      0 0.0.0.0:5666            0.0.0.0:*               LISTEN     
tcp6       0      0 :::5666                 :::*                    LISTEN 

Find the process or service listening on a particular port in Linux as follows (specify the port).

# netstat -ltnp | grep -w ':5666'
tcp6       0      0 :::5666                 :::*                    LISTEN      21537/nrpe

Using lsof Command:

# lsof -i :5666
COMMAND   PID USER   FD   TYPE   DEVICE SIZE/OFF NODE NAME
nrpe    21537 nrpe    4u  IPv4 24072633      0t0  TCP *:5666 (LISTEN)
nrpe    21537 nrpe    5u  IPv6 24072634      0t0  TCP *:5666 (LISTEN)

Using fuser:

fuser 80/tcp

To find out the PID of a process, you can use pidof

$ pidof firefox
$ pidof python
$ pidof cinnamon

Assuming you already know the PID of a process, you can print its name using the command form below:

ps -p PID -o format
  1. -p specifies the PID
  2. -o format enables a user-defined format

We will see how to find out a process name using its PID number with the help of user-defined format i.e comm= which means command name, same as the process name.

$ ps -p 2523 -o comm=
$ ps -p 2295 -o comm=

Related posts

Latest posts

Leave a Comment

Leave a Reply

Your email address will not be published. Required fields are marked *