Skip to content

[Linux] How To Check The Port is Used?

Last Updated on 2024-10-20 by Clay

Problem Description

We usually start various services on Linux servers, the most common being hosting a website or opening a port to allow us or users to test developing functionalities.

Anyway, whenever we use a port, conflicts are inevitable. A common example is, suppose I choose port 8888 to start my service, and then, oh no, my program has a bug, and the system crashes instantly. At this point, we might have to use the kill command to terminate the entire program.

Then, the problem arises: there is a scenario where, although we have terminated the service, the port is still being used by another process! When we run our service again, we encounter errors like Error: port is already in use.

Therefore, we need a way to check which ports are currently in use. This is the focus of this note.


Solutions

Here are several methods to check if a port is in use on a Linux system:

Method 1: Using the netstat Command

netstat (Network Statistics) is a commonly used command-line tool for displaying network connections, routing tables, and network interface statistics. To use netstat to check if a port is in use, you can use the following command:

netstat -tuln | grep <port_number>


This will list all processes currently using the specified port.


Method 2: Using the lsof Command

lsof (List Open Files) is a utility used to list currently open files on the system. To use lsof to check if a port is in use, you can use the following command:

lsof -i :<port_number>

This is the command I use most often to display ports that are in use. After all, it's similar to ls, so I specifically remember it XD


Method 3: Using the ss Command

ss (Socket Statistics) is a command-line tool used to retrieve information about socket statistics. To use ss to check if a port is in use, you can use the following command:

ss -tuln | grep <port_number>


A colleague told me about this command, and since it's ss, it's easy to remember.


References


Read More

Tags:

Leave a ReplyCancel reply

Exit mobile version