Find specific ports in use
From time to time I always try to spin up a quick server only to discover that
there is a process which is already using that specifc port that you’re trying
to acquire. A lot of the times, at least for me, those processes are not
attached to a TTY anymore so there’s no way to ctrl-c it and free the port. In
that case, you’d need to find the process and kill it with fire.
On macOS there’s a very simple command that you can use to immediately tell the PID which is bound to that port.
$ lsof -i :8000
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
Python 77918 matt 4u IPv6 0xb38865aa8736f21b 0t0 TCP *:irdmi (LISTEN)
This tells you that process 77918 is using port 8000 and is listening for
TCP connections on * all interfaces.
You can tell if a process has a tty attached by running
$ ps -p 77918 -o pid,tty
PID TTY
77918 ttys002
This is still attached to a terminal session so you can technically open that session and ctrl-c it, but in case the process is not attached to a tty you can claim that port back with
$ kill -p 77918