#!/usr/bin/perl use strict; use warnings; use Getopt::Long; # netstats.pl my $VERSION = 0.04; # originally posted at http://www.perlmonks.org/?node_id=1140950 # thanks to Discipulus from over at PerlMonks who # added the original usage output, added the remaining statuses # and added the Getopt::Long functionality my $platform = $^O; my @wanted = qw( ESTABLISHED SYN_SENT SYN_RECV FIN_WAIT1 FIN_WAIT2 TIME_WAIT CLOSE CLOSE_WAIT LAST_ACK LISTEN CLOSING UNKNOWN ); my %statuses = map { $_=> undef } @wanted; # platform specific status munging... my $listen; if ($platform eq 'MSWin32'){ $listen = 'LISTENING'; delete $statuses{LISTEN}; $statuses{$listen} = undef; } else { $listen = 'LISTEN'; } my $given_args = scalar @ARGV; my $auto = 0; if (grep {$_ =~ /-a|--auto/ } @ARGV){ $given_args -= 2; } unless ( GetOptions ( "ESTABLISHED|E" => \$statuses{ESTABLISHED}, "SYN_SENT|SS" => \$statuses{SYN_SENT}, "SYN_RECV|SR" => \$statuses{SYN_RECV}, "FIN_WAIT1|F1" => \$statuses{FIN_WAIT1}, "FIN_WAIT2|F2" => \$statuses{FIN_WAIT2}, "TIME_WAIT|TW" => \$statuses{TIME_WAIT}, "CLOSE|C" => \$statuses{CLOSE}, "CLOSE_WAIT|CW" => \$statuses{CLOSE_WAIT}, "LAST_ACK|LA" => \$statuses{LAST_ACK}, "LISTEN|L" => \$statuses{$listen}, "CLOSING|CG" => \$statuses{CLOSING}, "UNKNOWN|U" => \$statuses{UNKNOWN}, "auto|a=i" => \$auto, "help" => \&help, )) { help(); } if ($auto){ my $clear = $platform eq 'MSWin32' ? 'cls' : 'clear'; while (1){ system($clear); netstat(); sleep($auto); } } else { netstat(); } sub netstat { my @stat = split '\n', `netstat -nat`; if ($given_args == 0){map {$statuses{$_}=1} keys %statuses} my %data = map {$_ => 0} keys %statuses; for (@stat){ s/^\s+//; my $status; if ($platform eq 'MSWin32'){ $status = (split)[3]; } else { $status = (split)[5]; } next if ! $status; $data{$status}++ if defined $data{$status}; } map { printf "%10s\t$data{$_}\n ",$_} sort grep {defined $statuses{$_}} keys %statuses; } sub help { print "\nUSAGE $0:\n"; print <