Finding the pid listening on a specific port on Mac OS X

I’ve recently switched from Linux to Mac OS X and I’m trying to get used to the new environment. One of the differences from Linux is the way to find the process id (pid) listening on a specific port. In Linux you do like this:

to show the pid listening on port 8080. On Max OS X how ever you’ll run into the following error message:

The way to find the pid on the Mac is to do like this:

which will give us:

java 4582 johan 194u IPv6 0x1de155f6b2c74d03 0t0 TCP *:websm (LISTEN)

where 4582 is the pid listening on port 8080. The problem, for me at least, is that this is not a trivial command to remember. To make it simpler I wanted to add it as an alias in .bash_profile in my home directory. The problem now is that aliases won’t accept parameters the same way that bash scripts does (by using $@). This is actually not a problem if parameters should be added to the end of an alias. For example consider the following alias:

We’ve now aliased grep to be case-insensitive so when running for example

we can find the folder called foldername

But in our case the port parameter should not be appended at the end of our alias. So what we have to do to get around this is to first wrap the command in a function and then create an alias to that function:

You can now use pidport 8080 to find the pid of the process listening on port 8080. Prefix lsof with sudo to see process ids that you don’t own.

This Post Has 7 Comments

  1. yes but lsof lists open files – i have a case where netstat gives me some suspicious addresses but WILL NOT let me see the PID. And lsof will only work with open files – not those on last_ack. And wireshark can’t get to the PID


  2. Slightly simpler, there is no need for the alias. Give the shell function the name you actually want, and run it directly from the command line. Cheers!

    1. Thanks for the tip!

  3. I just saw this (thx) and man lsof states some more so this:

    lsof -n -iTCP:$port -sTCP:LISTEN -t

    returns only the pid of the process listening on port.
    The result can easily be used to kill the process.

  4. Good post

  5. Great post – saved me a lot of time moving to dev on OSX

Leave a Reply

Close Menu