views:

154

answers:

1

Xampp comes with a neat executable called xampp-portcheck.exe. This responds with if the ports required are free, and if not, which applications are running on those ports.

I can check if something is running on a port, by accessing the netstat details, but how do I find out the application running on the port within Windows?

+5  A: 

The CPAN module Win32::IPHelper provides access to GetExtendedTcpTable which provides the ProcessID for each connection.

Win32::Process::Info gives information about all running processes.

Combining the two, we get:

#!/usr/bin/perl

use strict;
use warnings;

use Win32;
use Win32::API;
use Win32::IPHelper;
use Win32::Process::Info qw( NT );

use Data::Dumper;

my @tcptable;

Win32::IPHelper::GetExtendedTcpTable(\@tcptable, 1);

my $pi = Win32::Process::Info->new;
my %pinfo = map {$_->{ProcessId} => $_ } $pi->GetProcInfo;

for my $conn ( @tcptable ) {
    my $pid = $conn->{ProcessId};
    $conn->{ProcessName} = $pinfo{$pid}->{Name};
    $conn->{ProcessExecutablePath} = $pinfo{$pid}->{ExecutablePath};
}

@tcptable =
    sort { $a->[0] cmp $b->[0] }
    map  {[ sprintf("%s:%s", $_->{LocalAddr}, $_->{LocalPort}) => $_ ]}
    @tcptable;

print Dumper \@tcptable;

Output:

  [
    '0.0.0.0:135',
    {
      'RemotePort' => 0,
      'LocalPort' => 135,
      'LocalAddr' => '0.0.0.0',
      'State' => 'LISTENING',
      'ProcessId' => 1836,
      'ProcessName' => 'svchost.exe',
      'ProcessExecutablePath' => 'C:\\WINDOWS\\system32\\svchost.exe',
      'RemoteAddr' => '0.0.0.0'
    }
  ],
  ...
  [
    '192.168.169.150:1841',
    {
      'RemotePort' => 80,
      'LocalPort' => 1841,
      'LocalAddr' => '192.168.169.150',
      'State' => 'ESTABLISHED',
      'ProcessId' => 1868,
      'ProcessName' => 'firefox.exe',
      'ProcessExecutablePath' => 'C:\\Program Files\\Mozilla Firefox\\firefox.exe',
      'RemoteAddr' => '69.59.196.211'
    }
  ],

Phewwww it was exhausting connecting all these dots.

Sinan Ünür