Displaying Full Command-Line Arguments for Listening Sockets on MacOS

I recently needed to figure out what process on my Mac was hogging a port I needed to utilize. Unfortunately a simple ‘netstat -l’ was useless because half of the processes were all simply ‘npm’. With a lot of LLM help I got this command working which shows all listening processes, by the command-line that started them, sorted by pid ascending.

sudo lsof -nP -iTCP -sTCP:LISTEN -F pcPn | awk '
  /^p/ {pid=substr($0,2); addrs[pid]=""}
  /^c/ {comm[pid]=substr($0,2)}
  /^n/ {addrs[pid]=(addrs[pid]?addrs[pid]" | ":"") substr($0,2)}
  END {
    for (p in comm) {
      cmd = "ps -p " p " -o pid=,user=,command=";
      cmd | getline full; close(cmd);
      printf "%-6s %-40s %s\n", p, addrs[p], full
    }
  }' | sort -n

Leave a comment