Skip to main content
Quick Tip

How to Find Open Ports and Close Them in Linux

Troubleshooting networks? Here's how to find the open ports and close those open ports in the Linux command line.

Sagar Sharma

Warp Terminal

So you are dealing with a critical server where you have to maintain security at any cost. And closing ports to block unwanted traffic is the first step you'd take.

Find open ports in Linux

In this tutorial, I am going to use the ss command to find open ports.

You can use the -l option with the ss command to get listening ports. But to be more specific, I'm going with -lt to get listening TCP ports:

ss -tl
list listening tcp ports in linux

Similarly, if you want to have a list of both TCP and UDP in the listening state, you can use the given command:

ss -tul
list of both TCP and UDP ports in the listening state

And to get the listening port of each service, you can use -n and for more fine-tuned results, you can always use the grep command:

ss -tuln | grep LISTEN
get listening port of currently running service

Enough of finding open ports, let's jump to how you can close them.

Close open ports in Linux

To close the port, first, you will need to stop the service and to find the service name, you can use the same ss command with -p option:

sudo ss -tulnp | grep LISTEN
find open ports with service names attactched to it

As you can see, the NGINX is utilizing port number 80. So let's stop it using the given command:

sudo systemctl stop nginx

As it will enable itself on every boot and you can alter this behavior using the given command:

sudo systemctl disable nginx

For better results, I would recommend changing firewall rules.

Here, I'm going to block port no 80 (used by NGINX) in UFW (which is pre-installed in Ubuntu).

First, let's check the status of UFW:

sudo ufw status
check status of ufw

And if it shows inactive, you can use the given command to enable it:

sudo ufw enable

Now, you just have to pair the deny option with the port number:

sudo ufw deny 80
deny nginx server from ufw

And here's the end result:

close port no 80

No sign of NGINX!

Wrapping Up

This was my take on how you can find and close open ports in Linux. I hope you will find this helpful.

And if you have any queries, let me know in the comments.

Sagar Sharma