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:

netstat -ntlp | grep 8080

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

netstat: option requires an argument -- p

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

lsof -n -i4TCP:8080 | grep LISTEN

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:

alias grep="grep -i"

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

ls -la | grep FolderName

we can find the folder called foldername

drwxr-xr-x   7 johan  staff     238 Sep  7 16:50 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:

pidportfunction() {
lsof -n -i4TCP:$1 | grep LISTEN

alias pidport=pidportfunction

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 8 Comments

  1. ian

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

    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. Johan Haleby

      Thanks for the tip!

  3. stan

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

    Good post

  5. Ben

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

  6. Sandy

    I’m sure 99% of people arrive here and copy/paste netstat -ntlp | grep 8080, just to find it doesn’t work. You could put a TLDR at top and show the one that does work.

Leave a Reply