Checking for Open and Used Ports

When managing a system, it’s essential to know which ports are open and in use. This information can be vital for security and troubleshooting purposes. Here are several methods to check for open and used ports on a system, depending on your operating system and preference.

Option 1: Using the lsof Command

The lsof command (List Open Files) is a versatile tool for listing information about files and processes. It can also be used to identify open network ports. Below are examples of how to use lsof:

1
2
3
4
5
6
7
8
# List all open ports and their associated processes
$ sudo lsof -i -P -n

# Filter for listening ports only
$ sudo lsof -i -P -n | grep LISTEN

# On OpenBSD, you can use `doas` instead of `sudo`
$ doas lsof -i -P -n | grep LISTEN

Option 2: Using the netstat Command

The netstat command is a classic tool for displaying network-related information. However, note that it has been deprecated on some Linux distributions in favor of the ss command. Here are examples for both Linux and FreeBSD/MacOS X:

Linux netstat Syntax:

1
2
3
4
5
6
# List all listening ports and their associated processes
$ netstat -tulpn | grep LISTEN

# Alternatively, use the `ss` command
$ sudo ss -tulw
$ sudo ss -tulwn

FreeBSD/MacOS X netstat Syntax:

1
2
3
4
5
# List all listening TCP ports
$ netstat -anp tcp | grep LISTEN

# List all listening UDP ports
$ netstat -anp udp | grep LISTEN

Option 3: Using the nmap Command

The nmap command is a powerful network scanning tool that can be used to discover open ports and services on a remote system. Here are examples of how to use nmap for this purpose:

1
2
3
4
5
6
7
8
# Scan for open TCP ports on localhost
$ sudo nmap -sT -O localhost

# Scan for open UDP ports on a specific IP address
$ sudo nmap -sU -O 192.168.2.13

# Scan for both open TCP and UDP ports in a single command
$ sudo nmap -sTU -O 192.168.2.13

These commands should help you determine which ports are open and actively in use on your system. Depending on your specific use case and operating system, you can choose the method that suits you best.

0%