top

Getting PID from Port in OpenSolaris

LSOF is a tool that's been available for ages, it can be used to "list open files". One of the nice things you can do with it is to list process IDs of a given TCP/UDP port. In Linux, people can use netstat to get this information. Solaris lacked this, so a good alternative is to use LSOF.

The basic command for that is, e.g. to search for port 7009:
lsof -i :7009

That should list the pid plus some other good information regarding that port number. A nice script we came across takes a full netstat output and maps the PID to each port:

#!/bin/sh

LSOF=/usr/local/bin/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

Save that to a file, and watch the nice output.

Solaris and OpenSolaris also have similar command, pfiles. You can also use pfiles (though it doesn't do exactly what we want) to lookup all the files and sockets being used by a given process id. You can query all the PIDs running on the system and capture the port number being used.

Another good alternative is using DTrace. It should be pretty easy to make use of say, the net provider, to capture traffic on a given port and then determine the process ID through that. In a future post, we can write up some more information on this.

0 Responses to Getting PID from Port in OpenSolaris

Leave a Reply

Mail will not be published