Who is hogging that port?

Every once in a while you want to know what process is running a server on some port, or even what processes are connected to some port. Here is how to find this kind of information on a linux system.
netstat -an | grep LISTEN
tcp        0      0 :::80                       :::*                        LISTEN      
tcp        0      0 :::22                       :::*                        LISTEN     
Actually you get a lot of other stuff too, but the above two lines show you that some process is serving on ports 80 and 22 (httpd and sshd).

How can we learn more?

[root@cholla linux]# lsof -i :22
COMMAND   PID USER   FD   TYPE  DEVICE SIZE/OFF NODE NAME
sshd     1753 root    3u  IPv4    6197      0t0  TCP *:ssh (LISTEN)
sshd     1753 root    4u  IPv6    6199      0t0  TCP *:ssh (LISTEN)
Again here we get other stuff also, but the above shows you that sshd is running as PID 1753. Unlike netstat, which can be run by any old user, this command will quietly return nothing if run as a regular user, you must be root when you run this command to get anything useful.

The netstat and lsof commands both have zillions of options and lots of other uses. The above lsof command defaults to looking for TCP sockets, if you had wanted UDP sockets, you might try:

lsof -i UDP:22

Cool script

Brandon Hutchinson put a cool little script online that maps listening TCP ports to process and PID. I reproduce it here, along with my tweaks to make it work on my system, and direct you to the above link to the original.

#!/bin/sh
# Map LISTENing TCP ports to their PIDs using lsof

LSOF=/usr/sbin/lsof

printf "%-6s %-10s %-6s %-8s\n" "Port" "Command" "PID" "User"
printf "%-6s %-10s %-6s %-8s\n" "----" "-------" "---" "----"

for PORT in `netstat -an | grep LISTEN | \
perl -ne 'print "$1\n" if /.*\.(\d+)\s+\*\.\*/' | sort -n | uniq`
do
    $LSOF -i :${PORT} 2>/dev/null | grep LISTEN | tail -1 | while read line
    do
	set $line
        COMMAND=$1
        PID=$2
        LSOF_USER=$3
        printf "%-6d %-10s %-6d %-8s\n" "$PORT" "$COMMAND" "$PID" "$LSOF_USER"
   done
done

Have any comments? Questions? Drop me a line!

Adventures in Computing / tom@mmto.org