Look who's talking, or: how to find which process listens on a given socket (Update #2)
From the "learn something new every day" department:
I've wondered how to find a process listening on a given
socket in the past. While there is "lsof" in pkgsrc,
here is a solution using NetBSD's on-board tools,
netstat(1) and fstat(1).
netstat(1)'s "-A" switch can be used to show a protocol
control block (PCB) associated with a socket in its
output, for TCP and Unix domain sockets:
% netstat -Aa
Active Internet connections (including servers)
PCB Proto Recv-Q Send-Q Local Address Foreign Address State
c15ce1f4 tcp 0 0 10.0.0.178.ssh mini.52788 ESTABLISHED
c15ce5dc tcp 0 0 *.ftp *.* LISTEN
c15ce7d0 tcp 0 0 *.https *.* LISTEN
...
Active Internet6 connections (including servers)
PCB Proto Recv-Q Send-Q Local Address Foreign Address (state)
c15ce3e8 tcp6 0 0 *.ftp *.* LISTEN
c15cedac tcp6 0 0 *.ssh *.* LISTEN
Active UNIX domain sockets
Address Type Recv-Q Send-Q Inode Conn Refs Nextref Addr
c1602480 stream 0 0 cb9e6f20 0 0 0 private/scache
...
Questions arising from the above output may be what process
is handling the TCP/ssh connection and
who is responsible for the "private/scache" Unix domain socket.
In NetBSD, a PCB identifies a certain network connection,
and from that more information on the processes using that
PCB can be determined.
This can be done using NetBSD's fstat(1) command
as follows.
The TCP ssh connection lists PCB "c15ce1f4":
% fstat | head -1
USER CMD PID FD MOUNT INUM MODE SZ|DV R/W
% fstat | grep c15ce1f4
feyrer sshd 23305 5* internet stream tcp c15ce1f4 10.0.0.178:22 <-> 10.0.0.2:52788
root sshd 26059 5* internet stream tcp c15ce1f4 10.0.0.178:22 <-> 10.0.0.2:52788
So it's two processes here, one SSH daemon running as root, and one
under my user-id. The reason behind this is the SSH daemon's
splitting of privileges across multiple processes.
The answer to who is listening on Unix domain socket
"private/scache" can be found in a similar fashion:
% fstat | grep c1602480
root master 511 80* unix stream c1602480
% locate /master | grep 'master$'
/usr/libexec/postfix/master
If a program "master" is not too obvious (a virus?!),
looking for its place on the file system, e.g. using
locate(1), may help. In this case, it shows that
the socket is used by the Postfix mail server.
Update 1+2:
Geert Hendricks mentioned "sockstat -l" as well...
one for the category "NetBSD commands you didn't know yet" :-)
Thanks Geert!
[Tags: fstat, netstat, sockstat]
|