How to Check for Open Ports in Linux

When you are troubleshooting networking issues in Linux or are looking for ways to improve the security of your Linux machine, you will need to know if and which ports are open. In this article we will look at different ways to list or display open ports in Linux.

What is a Port?

A port is a 16-bit number (0 to 65535) to help identify a given application or process on a Linux (Unix) operating system. Port differentiates one application from another on a Linux system.

Below are the different categories of ports:

  • 0 – 1023 – Referred to as Well Known Ports
  • 1024 – 49151 –Referred to as Registered Ports
  • 49152 – 65535 – Referred to as Dynamic Ports

Using the following command, a list of applications and ports is displayed on your terminal:

linux-port-services

TCP: TCP stands for Transmission Control Protocol. It is the most commonly-used protocol on the Internet. TCP is not just one-way communication, rather it sends packets back to acknowledge it’s received your packets.

UDP: Also known as User Datagram Protocol. It is an alternative communications protocol to TCP. The UDP protocol works similar to TCP. However, it ignores all error-checking stuff. UDP is necessary when speed is desirable and error correction is not needed.

SOCKETS: Socket allows communication from two different processes on the same or different machines.

Let’s look at different ways to list an open port in Linux.

1. Netstat

In this method we will use the command netstat -atu to check for open ports in Linux.

screenshot-from-2018-07-05-15-08-19

We used the -a-t and -u flags for netstat.

  • -a: shows all sockets
  • -t: shows TCP connections
  • -u: shows UDP connections

You can also add the -p flag to show related PID of the process or program name.

netstataupt

To display only UDP ports, you can use the following command:

netstatudp

Also, you can use the following command to search for TCP ports:

netstcp

2. lsof

Instead of using netstat, we can use the lsof command to display open ports in Linux:

lsof

The following command can also help to display open sockets:

lsofnp

Also, you can use the command below to list all TCP connections:

lsoftcp

Moreover, you can use the following command for UDP connections:

lsofudp

3. Network Mapped Command

In this method we will use nmap to detect the open port on your system. We can use the following command to show tcp port connections:

nmapst

Finally, to show udp port connections, we can use the following command:

nmaput

Conclusion

When it comes to the security of your Linux PC, the first thing to do is to close all unnecessary ports to prevent external access. With the methods listed above, you will be able to easily check for open ports on a Linux system and determine which ports should be closed or remain open.