Check occupied port

How to check if port is in use in

To check the listening ports and applications on Linux:

  1. Open a terminal application i.e. shell prompt.
  2. Run any one of the following command on Linux to see open ports:
    $ sudo lsof -i -P -n | grep LISTEN
    $ sudo netstat -tulpn | grep LISTEN
    $ sudo ss -tulpn | grep LISTEN
    $ sudo lsof -i:22 ## see a specific port such as 22 ##
    $ sudo nmap -sTU -O IP-address-Here
  3. For the latest version of Linux use the ss command. For example, ss -tulw

Let us see commands and its output in details.

Option #1: lsof command

The syntax is:
$ sudo lsof -i -P -n
$ sudo lsof -i -P -n | grep LISTEN
$ doas lsof -i -P -n | grep LISTEN # OpenBSD #

Sample outputs:

Fig.01: Check the listening ports and applications with lsof commandConsider the last line from above outputs:

sshd    85379     root    3u  IPv4 0xffff80000039e000      0t0  TCP 10.86.128.138:22 (LISTEN)
  • sshd is the name of the application.
  • 10.86.128.138 is the IP address to which sshd application bind to (LISTEN)
  • 22 is the TCP port that is being used (LISTEN)
  • 85379 is the process ID of the sshd process

Viewing the Internet network services list

The /etc/services is a text file mapping between human-friendly textual names for internet services and their underlying assigned port numbers and protocol types. Use the cat command or more command/less command to view it:
$ less /etc/services
A sample file:

tcpmux          1/tcp                           # TCP port service multiplexer
echo            7/tcp
echo            7/udp
discard         9/tcp           sink null
discard         9/udp           sink null
systat          11/tcp          users
daytime         13/tcp
daytime         13/udp
netstat         15/tcp
qotd            17/tcp          quote
chargen         19/tcp          ttytst source
chargen         19/udp          ttytst source
ftp-data        20/tcp
ftp             21/tcp
fsp             21/udp          fspd
ssh             22/tcp                          # SSH Remote Login Protocol
telnet          23/tcp
smtp            25/tcp          mail
time            37/tcp          timserver
time            37/udp          timserver
whois           43/tcp          nicname
tacacs          49/tcp                          # Login Host Protocol (TACACS)
tacacs          49/udp
domain          53/tcp                          # Domain Name Server
domain          53/udp

Each line describes one service, and is of the form:

#service-name   port/protocol   [aliases ...]
ssh             22/tcp                          # SSH Remote Login Protocol
time            37/tcp          timserver

Option #2: netstat or ss command

You can check the listening ports and applications with netstat as follows.

Linux netstat syntax

Prerequisite
By default, netstat

 command may not be installed on your system. Hence, use the apk command on Alpine Linux, dnf command/yum command on RHEL & co, apt command/apt-get command on Debian, Ubuntu & co, zypper command on SUSE/OpenSUSE, pacman command on Arch Linux to install the netstat

.Run the netstat command along with grep command to filter out port in LISTEN state:
$ netstat -tulpn | grep LISTEN
$ netstat -tulpn | more

OR filter out specific TCP port such as 443:
$ netstat -tulpn | grep ':443'
Where netstat command options are:

  • -t : Select all TCP ports
  • -u : Select all UDP ports
  • -l : Show listening server sockets (open TCP and UDP ports in listing state)
  • -p : Display PID/Program name for sockets. In other words, this option tells who opened the TCP or UDP port. For example, on my system, Nginx opened TCP port 80/443, so I will /usr/sbin/nginx or its PID.
  • -n : Don’t resolve name (avoid dns lookup, this speed up the netstat on busy Linux/Unix servers)
Linux check if port is in use using ss command

The netstat command deprecated for some time on Linux. Therefore, you need to use the ss command as follows:
$ sudo ss -tulw
$ sudo ss -tulwn
$ sudo ss -tulwn | grep LISTEN


Where, ss command options are as follows:

  • -t : Show only TCP sockets on Linux
  • -u : Display only UDP sockets on Linux
  • -l : Show listening sockets. For example, TCP port 22 is opened by SSHD server.
  • -p : List process name that opened sockets
  • -n : Don’t resolve service names i.e. don’t use DNS

Related: Linux Find Out Which Process Is Listening Upon a Port

FreeBSD/macOS (OS X) netstat syntax

The syntax is as follows:
$ netstat -anp tcp | grep LISTEN
$ netstat -anp udp | grep LISTEN

You can use the sockstat command on macOS or FreeBSD to display open TCP or UDP ports too. For example:
{vivek@freebsd13-server:~}$ sudo sockstat -4 -6 -l
Outputs from my FreeBSD server version 13.xx:

USER     COMMAND    PID   FD PROTO  LOCAL ADDRESS         FOREIGN ADDRESS      
root     master     1723  13 tcp4   127.0.0.1:25          *:*
root     master     1723  14 tcp4   192.168.2.20:25       *:*
root     sshd       1627  3  tcp6   *:22                  *:*
root     sshd       1627  4  tcp4   *:22                  *:*
ntpd     ntpd       1615  20 udp6   *:123                 *:*
ntpd     ntpd       1615  21 udp4   *:123                 *:*
ntpd     ntpd       1615  22 udp4   192.168.2.20:123      *:*
ntpd     ntpd       1615  23 udp6   ::1:123               *:*
ntpd     ntpd       1615  24 udp6   fe80::1%lo0:123       *:*
ntpd     ntpd       1615  25 udp4   127.0.0.1:123         *:*
ntpd     ntpd       1615  26 udp4   172.16.0.5:123        *:*
root     syslogd    1085  6  udp6   *:514                 *:*
root     syslogd    1085  7  udp4   *:514                 *:*
?        ?          ?     ?  udp4   *:17890               *:*
?        ?          ?     ?  udp6   *:17890               *:*

OpenBSD netstat syntax

$ netstat -na -f inet | grep LISTEN
$ netstat -nat | grep LISTEN

Option #3: nmap command

The syntax is:
$ sudo nmap -sT -O localhost
# search for open port IP address 192.168.2.13
$ sudo nmap -sU -O 192.168.2.13 ##[ list open UDP ports ]
$ sudo nmap -sT -O 192.168.2.13 ##[ list open TCP ports ]

Fig.02: Determines which ports are listening for TCP connections using nmapYou can combine TCP/UDP scan in a single command:
$ sudo nmap -sTU -O 192.168.2.13

A note about Windows users

You can check port usage from Windows operating system using following command:
$ netstat -bano | more
$ netstat -bano | grep LISTENING
$ netstat -bano | findstr /R /C:"[LISTEING]"

Testing if a port is open from a bash script

One can use the “/dev/tcp/{HostName}_OR_{IPAddrress}>/{port}” syntax to check if a TCP port is open on a Linux or Unix machine when using Bash. In other words, the following is Bash specific feature. Let us see if TCP port 22 is open on localhost and 192.168.2.20:
$ (echo >/dev/tcp/localhost/23) &>/dev/null && echo "open" || echo "close"
$ (echo >/dev/tcp/192.168.2.20/22) &>/dev/null && echo "open" || echo "close"

Now we can build some logic as follows:

12345678910#!/bin/bashdest_box="aws-prod-server-42"echo"Testing the ssh connectivity ... "if! (echo>/dev/tcp/$dest_box/22) &>/dev/nullthen    echo"$0 cannot connect to the $dest_box. Check your vpn connectivity."else    echo"Running the ansible playboook ..."    ansible-playbook -i hosts --ask-vault-pass --extra-vars '@cluster.data.yml'main.yamlfi

What if I’m not using Bash…

Try the nc command as follows:
$ nc -w {timeout} -zv {server_IP_hostname} {tcp_port} &>/dev/null && echo "Open" || echo "Close"
$ nc -w 5 -zv 192.168.2.20 23 &>/dev/null && echo "TCP/23 Open" || echo "TCP/23 Close"

The updated Bash script:

123456789101112131415161718#!/bin/bashdest_box="aws-prod-server-42"timeout="5"# timeouts in secondsecho"Testing the ssh connectivity in $timeout seconds ... "# make sure 'nc' is installed, else die ..if! type-a nc&>/dev/nullthen    echo"$0 - nc command not found. Please install nc and run the script again."    exit1fiifnc-w "$timeout"-zv "${dest_box}"22  &>/dev/nullthen    echo"$0 cannot connect to the $dest_box. Check your vpn connectivity."    exit1else    echo"Running the ansible playboook ..."    ansible-playbook -i hosts --ask-vault-pass --extra-vars '@cluster.data.yml'main.yamlfi

More examples & source post: https://www.cyberciti.biz/faq/unix-linux-check-if-port-is-in-use-command/