#!/usr/bin/perl -w

use strict;

my %inode_pid;
my %inode_cmd;
my $fname="/proc/voltaire/sdp-sockets/ib-socket-netstat";
my $field=4;

if ( ! -f $fname ) {
    print "no IB sockets data.\n";
    exit 1;
}

for my $proc_pid (</proc/[0-9]*[0-9]>) {
	my $pid = $proc_pid;
	$pid =~ s,/proc/,,;
	# print "pid: $pid\n";
	for my $proc_fd ( <${proc_pid}/fd/*> ) {
		my $fd = $proc_fd;
		$fd =~ s,/proc/\d*/fd/,,;
		my $link_data = readlink ($proc_fd);
		# print ("pid: $pid, $fd, $link_data\n");
		# socket:[2708]
		if ( defined ($link_data) && $link_data =~ /socket/ ) {
			# print "socket found: $link_data\n";
			if ( $link_data =~ /\[(\d+)\]/ ) {
				my $inode = $1;
				$inode_pid{$inode} = $pid;
				$inode_cmd{$inode} = qx{cat $proc_pid/cmdline};
				# print "inode: $inode\n";
			}
		}
        }
}

if ( -f $fname ) {
    open S, "<$fname" or die ("cant open $fname");
    while (<S>) {
	s/^\s+//;
	s/[\s\n\r]+$//;
	my @f = split /\s+/;
	next if ! @f;
	next if !defined ($f[${field}]) || $f[${field}] !~/^\d+$/ ||  $f[${field}] == 0;
	printf "%s %d/%s\n", $_, $inode_pid{$f[${field}]}, $inode_cmd{$f[${field}]};
	# printf "%s: i: %d p: %d cmd: %s\n", $_, $f[${field}], $inode_pid{$f[${field}]}, $inode_cmd{$f[${field}]};
	# print "$_ : @f\n";
    }
    close (S);
} else {
    print "IB sockets data is missing.\n";
    # print "inode: $_, pid: $inode_pid{$_}, cmd: $inode_cmd{$_}\n" for sort keys %inode_pid;
}

exit 0;
