I stumbled across this answer while looking at this stack overflow post. I thought it was such a great solution to my problem that I decided to write a blog post about it to help me not forget it.
Lsof To The Rescue
The linux command lsof stands for "list open files", and it's useful in this situation because it lists which files are open and by which processes.
Filtering For A Given Port
If you just type in lsof into your command line and hit enter you might have a heart attack from the amount of information that gets dumped into the command propmt. Let's filter some stuff out so that it only shows us what we care about. In this case I only care about processes running on port 4200 (yep, it's an Angular 2 CLI app. hehe). We can use the -i flag with lsof to show only files open for a given port:
Why the Colon?
Notice the colon prefixing the port number above. It would result in an error if you tried to run "lsof -i 4200", and the error would be, "lsof: unknown protocol name (200) in: -i 4200". We need to specify some protocol like TCP, UDP, etc. In my case I'm actually using TCP protocol so this command would work as well:
The trick is that if you don't know the protocol and want to look up processes running on a given port for any protocol then you can just leave off the protocol but keep the colon, resulting is a sort of shortcut wildcard syntax.
The posts on this site are written and maintained by Jim Lynch. About Jim...