To get process id for port number

Hi All,

How to get the list of port numbers and it is correspoding proceses id that are currently running on. Please suggest and it is urgent

Thanks.

The tool you want is lsof (list open file), which will see processes on sockets, tell you the remote end, etc.

1 Like

lsof is not normally on Solaris. You can install the package for it.
Where srchp is the port number... you have to be root to do this, and it is not very efficient.

srchp=14002
ptree -a | awk '{print $1} ' |while read pid
 do
   pfiles $pid | /usr/xpg4/bin/grep -q "$srchp"  && echo $pid
 done
2 Likes

Can you find sockets in /proc/?

1 Like

Yes. sockets are represented as file descriptors.

1 Like

This is the shell function I'm using:

function sockpid
{
  pfiles /proc/* | nawk '
  /^[0-9]*:/  { process=$0 }
  /^ [0-9]*:/ { descriptor=$1 }
  /port: '$1'/ { printf("pid: %-40s fd: %s %s\n",process,descriptor,$0);}'
}

eg:

# sockpid 22
pid: 548:       /usr/lib/ssh/sshd                   fd: 256:    sockname: AF_INET6 ::  port: 22
# sockpid | head
pid: 379:       /usr/sbin/in.routed                 fd: 257:    sockname: AF_INET 0.0.0.0  port: 520
pid: 379:       /usr/sbin/in.routed                 fd: 257:    sockname: AF_INET 0.0.0.0  port: 0
pid: 387:       /usr/sbin/named                     fd: 257:    sockname: AF_INET 127.0.0.1  port: 53
pid: 387:       /usr/sbin/named                     fd: 257:    sockname: AF_INET 10.0.2.15  port: 53
pid: 387:       /usr/sbin/named                     fd: 257:    sockname: AF_INET 127.0.0.1  port: 953
pid: 387:       /usr/sbin/named                     fd: 512:    sockname: AF_INET 127.0.0.1  port: 53
pid: 387:       /usr/sbin/named                     fd: 513:    sockname: AF_INET 10.0.2.15  port: 53
pid: 400:       /usr/lib/nfs/statd                  fd: 256:    sockname: AF_INET 0.0.0.0  port: 0
pid: 447:       /usr/lib/inet/inetd start           fd: 256:    sockname: AF_INET6 ::  port: 23
pid: 447:       /usr/lib/inet/inetd start           fd: 256:    sockname: AF_INET6 ::  port: 7008
# 
2 Likes

How about: lsof -i [:port]

$ lsof -i :8080
COMMAND   PID     USER   FD   TYPE        DEVICE SIZE/OFF NODE NAME
java    19483 username   27u  IPv4 0x3021febbcc0      0t0  TCP *:8080 (LISTEN)

EDIT: Please disregard. I misread the requirement, I thought the OP want to get PID for particular PORT

1 Like

Thanks all.