Tuesday, September 18, 2007

Matching a TCP port to a process PID.

In Linux there is:

"lsof -p $PID-a -i 4 2" to list all ports used by a process


"lsof -i 4:$PORT" to list which process is using a port.

The problems is that the Solaris port of lsof is broken and cannot match ports/pids. Also, lsof isn't in Solaris, being a 3rd party application you need to install yourself (blastwave, etc).

Netstat doesn't help us either, but there are 2 native Solaris tools that do: pfiles and fuser.

for x in `ps -ef | awk ' { print $2 } '`; do echo PID: $x ; pfiles $x | grep "port: "; done


ps -e -o pid | xargs -t -n1 pfiles | grep "port: $PORT"

Another interesting alternative is PCP (it basically does the same thing, but adds some indentation and such):

PCP is a script that enables administrators to see what open TCP ports are in use on a Solaris system. It maps ports to PIDs and vice versa. It accepts wildcards and will also show at a glance all open ports and their corresponding PIDs. I wrote it because I couldn't install lsof where I was working, and "lsof -i" is a great addition to any UNIX admin's toolbox. PCP is a half-decent alternative.


Chan Kok Leong said...

Thanks from you blog entry, it was informative