Linux: find used ports quickly

If you work with Linux most likely you had to troubleshoot why and application is not starting, one reason would be that the port must bind…

Linux: find used ports quickly
Photo by Lukas on Unsplash

If you work with Linux most likely you had to troubleshoot why and application is not starting, one reason would be that the port must bind is already used by another process, lets see how you can easily identify if is already used.

The ss command

The ss command is used to print socket statistics, it is installed by default in most modern Linux distros, the command that has replaced was netstat, i will not explain how ss can be used in general but i will present you an one-liner that can be used as an alias to your bashrc profile for quick investigations.

The one liner

ss -tulpn | grep LISTEN | tr -s " " | cut -d " " -f5 | rev | cut -d ":" -f1 | rev

This command will do the following

  1. ss will print all listening TCP and UDP ports
  2. grep will print only LISTEN sockets
  3. tr will squeeze multiple spaces to one
  4. we select only the fifth column
  5. we reverse the string to make it easier to get only the port number
  6. using cut again allows us to select the port number which is : delimited
  7. we reverse text again

This is the expected output, each number is a port already used by a process.

ss -tulpn | grep LISTEN | tr -s " " | cut -d " " -f5 | rev | cut -d ":" -f1 | rev  
9099 
10256 
45393 
53 
631 
19001 
1338 
10248 
10249 
10257 
10259 
3350 
631 
16443 
3389 
25000 
10250

How to make this one-liner an alias

Open ~/.bashrc using your favorite editor and add the following to the end of the file

alias usedports='ss -tulpn | grep LISTEN | tr -s " " | cut -d " " -f5 | rev | cut -d ":" -f1 | rev'

Reload ~/.basrc for changes to take effect

 $ source ~/.bashrc

Using the alias is very straight forward, just type the name and press enter

$ usedports 
9099 
10256 
45393 
53 
631 
19001 
1338 
10248 
10249 
10257 
10259 
3350 
631 
16443 
3389 
25000 
10250

I hope you enjoyed this short article!

Join Medium with my referral link - Konstantinos Patronas
As a Medium member, a portion of your membership fee goes to writers you read, and you get full access to every story…