Figuring Out What's Using a Port

Here's a quick and easy (to use) way to figure out what process is using a particular TCP port. This can be rather handy when you're trying to start a new daemon or service, and it complains that it can't bind to the port.

fuser 143/tcp | awk '{print $2}' | xargs ps ho cmd

In this case, it'll tell you what process is using port 143, the IMAP port. Substitute whatever port you're interested in for 143 (and replace tcp with udp for UDP ports, of course). You should generally run this as root, or else it'll only be able to tell you about ports belonging to your own processes.

Member Lonny Selinger wrote a handy little Perl script that accomplishes the same thing. It's available from the FTP site.

Note that the syntax used here is somewhat specific to Linux. If you want to do this on non-Linux systems, read the manpages for fuser(1) and ps(1) for the exact syntax used by your system.

Another way to do the same thing is to use a program called lsof which lists open files and compiles on a slew of unices. You can use -i to specify which protocol and port to examine, it will then return a list of the processes using said port.

Examples: lsof -i :ssh will list all processes using whichever port /etc/services associates with the service named ssh. lsof -i UDP:53 lists those processes that fancy UDP port 53 (tends to be named).