Skip to content

Instantly share code, notes, and snippets.

@rollwagen
Last active August 28, 2024 15:45
Show Gist options
  • Save rollwagen/633279f480064c45820d8638010d36ef to your computer and use it in GitHub Desktop.
Save rollwagen/633279f480064c45820d8638010d36ef to your computer and use it in GitHub Desktop.
lsof / netstat on macos

lsof / netstat on macos

lsof - list open files

  • display (list) all open TCP+UDP ports and grep for listening ones

    • sudo lsof -i -P | grep LISTEN
      COMMAND     PID           USER   FD   TYPE             DEVICE SIZE/OFF   NODE NAME
      launchd       1           root   11u  IPv6 0x26dd73cb700390df      0t0    TCP *:22 (LISTEN)
      ....
    • Note: (1) will take long as IPs are resolved (DNS) (2) also lists all ports <1024 (b/c of sudo)
  • same as above but only IPv4 and only TCP; do not resolve IPs (-n)

    • sudo lsof -nP -i4TCP:$PORT | grep LISTEN
  • again, same/similar as above but only for UDP * sudo lsof -nP -i4TCP | grep LISTEN

  • list only network files with TCP state LISTEN:

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

Note: Need sudo if you want information on ports below 1024.

  • display command/pid listening on spedific port

    • lsof -i :PORT
    • Example: lsof -i :2222
      COMMAND     PID      USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME
      qemu-syst 82109 rollwagen   15u  IPv4 0x26dd73cba9252767      0t0  TCP *:rockwell-csp2 (LISTEN)
    • Note: remember need to be root if port < 1024
  • lsof options used; see man 8 lsof for details -n - IP addresses instead of host names (otherwise slow b/c of DNS lookups for IPs)
    -P - raw port numbers instead of name such as https, ftp
    -i - for IPv4 and IPv6 protocols \

netstat

  • List details (protocol, pid) of specific listening port
    • netstat -anv | egrep -w [.]2222.*LISTEN (first lines/header copied in to show captions)
      Active Internet connections (including servers)
      Proto Recv-Q Send-Q  Local Address          Foreign Address        (state)     rhiwat shiwat    pid   epid  state    options
      tcp4       0      0  *.2222                 *.*                    LISTEN      131072 131072  82109      0 0x0000 0x00000106
  • netstat options used; see man netsat for details -a show the state of all sockets
    -n don't resolve IPs
    -v increase verbosity

ps -eaf | grep lsof -t -i:8000

  • can also use ps and pipe to lsof to show full CMD output including all parameters
  $ ps -eaf | grep `lsof -t -i:8000`

  UID   PID  PPID   C STIME   TTY           TIME CMD
  501 32091 58150   0 10:40AM ttys001    0:00.20 /Users/rollwagen/.pyenv/versions/3.9.4/bin/python -m http.server

Links / references

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment