Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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
share|improve this question

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).

share|improve this answer

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).

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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