MacOS
MacOS is kinda weird, well it uses BSD-based netstat, so you will find some tools you are used to running on Linux won’t translate 1:1.
netstat
Here is the closest equivalent to “netstat -tln” on Linux on macOS :
netstat -p tcp -van | grep '^Proto\|LISTEN'
tuoptions are not available, but they can be replaced by either-p tcpor-p udp, although you can’t have both at the same time-poption is replaced with-vwhich effectively gets you PIDs listed-loption is not available, but you can work around it by using-aoption (which includes servers in the listing) andgrep LISTEN(to filter only for listening)
lsof
| The equivalent output of running “netstat | grep LISTEN” on Linux: |
lsof -iTCP -sTCP:LISTEN
“What is running on port X ?”
Note: Need sudo if you want information on ports below 1024
On recent MacOS, use this command:
sudo lsof -i -P | grep LISTEN | grep :$PORT
or to see just IPv4:
sudo lsof -nP -i4TCP:$PORT | grep LISTEN
similar to above but only for UDP
sudo lsof -nP -i4TCP | grep LISTEN
On older versions, you may need to run one of the following forms:
sudo lsof -nP -iTCP:$PORT | grep LISTEN
sudo lsof -nP -i:$PORT | grep LISTEN
Grep on Grep:
# display (list) all open TCP+UDP ports and grep for listening ones
sudo lsof -i -P | grep LISTEN
# further grep that list to a specific $PORT
sudo lsof -i -P | grep LISTEN | grep :$PORT
For example, to find and kill the process occupying port 3000
# Find:
sudo lsof -i :3000
# Kill:
kill -9 <PID>
You 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/penguin/.pyenv/versions/3.X.X/bin/python -m http.server