MacOS – How to find which process has opened the port on macOS

macosNetwork

using netstat we can find LISTENing or open port etc.
I want to know how can we find out which process has opened which port we see in the result of

netstat -vanp tcp

Best Answer

As @klanomath mentioned in a comment, the output from netstat -vanp tcp contains the process ID of the process that has the port open (it's the next-to-last field), so you can look it up by that:

$ netstat -vanp tcp
Active Internet connections (including servers)
Proto Recv-Q Send-Q  Local Address          Foreign Address        (state)     rhiwat shiwat    pid   epid
...
tcp4       0      0  127.0.0.1.631          *.*                    LISTEN      131072 131072  14636      0
                                                                                              ^^^^^
$ ps 14636
  PID   TT  STAT      TIME COMMAND
14636   ??  Ss     3:55.43 /usr/sbin/cupsd -l

So in this example, it's cupsd (the Common UNIX Printing System Daemon) listening on port 631 (for IPP, the Internet Printing Protocol).

You can also use lsof -i, with many options to narrow down the search; see man lsof for details. But note that you need to run it as root (i.e. with sudo) to see processes you don't own:

$ sudo lsof -i :631
Password: [admin password doesn't echo]
COMMAND   PID USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME
cupsd   14636 root    5u  IPv6 0xc9c73d98b1fafae5      0t0  TCP localhost:ipp (LISTEN)
cupsd   14636 root    6u  IPv4 0xc9c73d98b3b2548d      0t0  TCP localhost:ipp (LISTEN)