I have several applications that run on random ports. How would I take the pid or the file location and find which port it is running on?

Example of desired output:

www-data/apache = 80
my-awesome-game = 2023

I would use

# netstat -anp

The option -p displays the related PID and the name of the program to which the related socket belongs. You just need to grep the output to filter only the lines you need (by PID or program name).


In a similar way as netstat, lsof could also do the trick:

lsof -i

You'll have to grep the output for finding the PID you want.

The advantage I see using lsof is that '-p' in netstat doesn't work for all Unix flavors, I happen to manage AIX, Solaris and HP-UX (besides Red Hat) and use lsof cause all parameters are the same even though some features don't work as they should (i.e. having propietary and non-standard filesystems could cause trouble finding file names or other information).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.