Last Updated: February 25, 2016
·
695
· shrayas

Check what is running on a given port

I've always wanted to know which command is running on a given port. Today i think i managed to get my head around it.

This is the command:

ps -ef | grep $(netstat -pan | grep ":5000" | awk '{print $7}' | cut -d "/" -f1)

Now on to the explanation

Step 1

We will start from the inner most set of commands i.e. netstat -pan | grep ":5000" | awk '{print $7}' | cut -d "/" -f1

netstat -pan shows the current list of open connections in a certain format. The -p flag shows the PIDS. The -a flag shows all connections. The -n flag shows it in numbered format

The grep ":5000" command is searching for a given port (this is what needs to be parameterized in case you're using this within a shell script or something

The awk '{print $7}' prints the 7th set from the output after splitting by whitespace

The cut -d "/" -f1 cuts the output on a / character and prints the first split

The final output will be a PID

Step 2

Now on to the surrounding part. The ps -ef command lists all the processes in a well formatted way. This output is then piped through to a grep command whose input is the output obtained in Step 1

Voila, we've arrived at the line we wanted.