How to use netstat to show what process is listening on a port

I'm on an OS X Mountain Lion laptop and have a couple of Vagrant boxes on it. I'm trying to figure out which process is listening on port 8080. My variations produce like a hundred lines but none with specific port number. I'm assuming something like:

netstat -XXX | grep 8080

Solution 1:

Unfortunately on OSX you're stuck with the BSD netstat which will not show you the process ID that is attached to a given port. What you have to do instead is use lsof. The syntax you'll need to use is:

lsof -i :8080

This will print out gobs of information, most of which you don't care about, but the fields are well labeled. For example, check out this example output.

lsof -i :53237
COMMAND   PID  USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME
GoogleTal 927 guest   29u  IPv4 0x2c3f7f95244855c3      0t0  TCP localhost:53237 (LISTEN)

This tells me that port 53237 is in use by process ID 927. When reading the COMMAND field keep in mind that this output is truncated, in reality the full name of the binary is GoogleTalkPlugin.

Solution 2:

This is what I like to use when looking for a listening port's PID. For Linux use: netstat -tunlp

  • n network
  • l listening ports
  • p process
  • t tcp
  • u udp

Additional information can be found in the man pages.

Solution 3:

I was in the process of modifying netstat on OS X to provide this feature and stumbled upon the fact that -v will give you the pid associated with a socket.