[Nottingham] Unix process open sockets

Michael Erskine (at home!) perl at tecspy.com
Fri Jan 4 22:41:39 GMT 2008


Phil Court wrote:
> Is there a way using perl that, given a process Id ($pid) I can 
> retrieve/display all the
> associated sockets (unix/internet) of the corresponding unix process ?ing perl that, given a process Id ($pid) I can retrieve/display all the
associated sockets (unix/internet) of the corresponding unix process ?

Sure, many ways! I'd grab the output of lsof -p $pid...

#!/usr/bin/perl -w
use strict;
use IO::Socket;

my $pid = shift || $$;

print "Open sockets for process id $pid...\n";
# An example server and client socket pair to test on $$...
my ($host, $port) = ('127.0.0.1', 9999);
my $server = IO::Socket::INET->new(LocalPort => $port,
                                 Type      => SOCK_STREAM,
                                 Reuse     => 1,
                                 Listen    => 10 )   # or SOMAXCONN
     or die "Couldn't be a tcp server on port $port : $@\n";
my $client = IO::Socket::INET->new(PeerAddr => $host,
                                 PeerPort => $port,
                                 Proto    => "tcp",
                                 Type     => SOCK_STREAM)
     or die "Couldn't connect to $host:$port : $@\n";
my $s = $server->accept();
# and a suitable lsof call (should use -i[4][6] -a -U or somesuch)...
my $cmd = "lsof -n -p $pid";
# could use backticks to capture the output...
system $cmd;

Now go read the lsof(1) manpage!
Regards,
Michael Erskine.




More information about the Nottingham mailing list