Quick post to highlight the bash tool lsof, which stands for stands for list open files.

It is capable of many things, but one handy use is to find any “file” that is using a specific internet address on your system.

For example, say you started a server in the background and started doing some dev work. Now you need to quickly find the process and kill it so it can be restarted.

Using the -i flag allows us to search only network files, and we can further filter it down with these options:

[46] # for IPv4 or IPv6
[protocol] TCP
[@hostname|hostaddr]
[:service|port]

Some examples:

# to find all processes running on localhost
lsof -i tcp@localhost

# to find a process by port
lsof -i tcp:4000

# combine them
lsof -i tcp@0.0.0.0:4000

Your system may display processes that are no longer running. The -s flag is available in some versions of bash, and allows us to filter a list of processes by their state. Possible states include CLOSED, IDLE, BOUND, LISTEN, ESTABLISHED. An active http server I am running on my system has the state of LISTEN and is on port 4000. let’s find that process by port, grab its process id with awk (column 2, row 2) and kill it

lsof -i TCP:4000 -sTCP:LISTEN | awk 'FNR==2 {print $2}' | xargs kill -9