Friday, February 6, 2009

Enumerating TCP Connections

What I was looking for is a simple script to capture all new ("Established") connections.  This could use some improve since my code has some side-effects.  'Compare-object' subtracts the diff between two arrays: the reference set and the difference set. To run this I type this at a PS prompt:
  • function Est_do {do {Established} while (1)}
  • Est_do | out-file $pwd\Established.txt

function global:Established 
{
    Begin
    {
    $a = [System.Net.NetworkInformation.IPGlobalProperties]::GetIPGlobalProperties()
    }
    Process
    {
    if ($b -ne $null) {$last_b = $b}
    $b = $a.GetActiveTcpConnections()   | where{$_.State -eq "Established" }  
    if ($last_b -ne $null) 
        {$c = compare-object $last_b $b;
            if ($c.SideIndicator -eq "=>" ) {write $c.InputObject | ft -HideTableHeaders}       
        }
   $global:last_b = $b
      }
    End 
    {
    start-sleep -m 250
    }  
}


[Established.txt] :

Established 192.168.0.8:3419 209.85.147.83:80
Established 192.168.0.8:3420 74.125.19.191:80
Established 192.168.0.8:3422 74.125.19.191:80
...

No comments: