I am trying to get all the processes listening for a network connection on Mac OS X. netstat does not have the -p option and I am trying with lsof

lsof -i -sTCP:LISTEN

gives me a fair list of listening processes but not all. I can for example telnet to port 10080 where I have a process listening for a connection but this is not shown in the output of lsof. What am I missing?

$ telnet localhost 10080
Trying ::1...
Connected to localhost.
Escape character is '^]'.
telnet> Connection closed.


$ sudo lsof -n -i | grep 10080
  • 3
    Does the output of lsof say amanda instead of 10080?
    – Jon Lin
    Dec 15, 2011 at 13:56
  • 4
    @JonLin I didn't notice that the -n only affects addresses and not ports. To get port numbers I have to use -P too. Thanks
    – Matteo
    Dec 15, 2011 at 14:35
  • 3
    @JonLin: but you have post lsof -i -sTCP:LISTEN , and it without the -n and it didn't reveal the 10080 too. So you have to use the -P.
    – Hanan N.
    Dec 15, 2011 at 17:30

3 Answers 3

sudo lsof -iTCP -sTCP:LISTEN
sudo lsof -iTCP -sTCP:LISTEN -P
sudo lsof -iTCP -sTCP:LISTEN -P -n
sudo lsof -iTCP -sTCP:LISTEN -n

All return the same 32 entries (... | wc -l) on my heavily used Lion MBP.

-P -n prevents lsof from doing name resolution, and it doesn't block. Missing either one of these, it can be very slow.

For UDP: sudo lsof -iUDP -P -n | egrep -v '(127|::1)'. Without -n and -P, it takes a long time.

Reminder: This does not include firewall settings.

  • 3
    Yes the problem was the missing -P. I wrongly assumed -n applied not only to IPs but port numbers too.
    – Matteo
    Dec 29, 2011 at 7:04

sudo lsof -nP -iTCP -sTCP:LISTEN

This command shows all network files, listening with TCP protocol on all the open ports.

sudo lsof -nP -iTCP:5432 -sTCP:LISTEN

This command just shows the one listening on port 5432


I wrote this shell function you can stick in your ~/.bashrc that gives you a nice report:

ports() {
        echo 'PROC PID USER x IPV x x PROTO BIND PORT'
            sudo lsof +c 15 -iTCP -sTCP:LISTEN -P -n | tail -n +2
            sudo lsof +c 15 -iUDP -P -n | tail -n +2 | egrep -v ' (127\.0\.0\.1|\[::1\]):'
        ) | sed -E 's/ ([^ ]+):/ \1 /' | sort -k8,8 -k5,5 -k1,1 -k10,10n
    ) | awk '{ printf "%-16s %-6s %-9s %-5s %-7s %s:%s\n",$1,$2,$3,$5,$8,$9,$10 }'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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