What's using that port on Mac OS X?

It happens to us all.  We run a web app locally when we’re developing or testing, get distracted and leave the app container running.  The next time we run the same time, we get the following message:

java.net.BindException: Address already in use

usually on port 8080.  The question is, how do we find out which process is using that port and how do we clear it?

On Mac OS X (and indeed on any Unix-style platform), we use the command:

sudo lsof -i:<port number>

This then brings up a load of useful information about which process is hogging our port including, most importantly, the PID.  From there it’s a simple case of either using the Activity Monitor to Force Quit the process, or from the command line use

kill <PID>

or

kill -9 <PID>