#!/usr/bin/perl
# rrd-netstat.pl
# v2.0 Nicolas AGIUS - 03/2010
# Usage : rrd-netstat.pl 
#
###################################################################################
## Sonde RRD pour le nombre de connections réseaux
#
# Copyright (C) 2006 Nicolas AGIUS <nicolas_agius@yahoo.fr>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
#
###################################################################################


my @tcp_states = ("TIME_WAIT","ESTABLISHED","CLOSE","CLOSE_WAIT","FIN_WAIT","LAST_ACK","SYN_RECV","SYN_SENT");
my @udp_states = ("ASSURED","UNREPLIED");

my %tcp_count, %udp_count;

# Initialize 
foreach(@tcp_states) { $tcp_count{$_}=0; }
foreach(@udp_states) { $udp_count{$_}=0; }

open(STAT,"</proc/net/nf_conntrack") or die "Cannot open /proc/net/nf_conntrack";
LOOP: while(<STAT>)
{
	foreach $state (@udp_states)
	{
		if(/udp.*$state/)
		{
			$udp_count{$state}++;
			next LOOP;
		}
	}

	foreach $state (@tcp_states)
	{
		if(/tcp.*$state/)
		{
			$tcp_count{$state}++;
			next LOOP;
		}
	}

}
close(STAT);


# Print TCP stats
foreach(keys(%tcp_count))
{
	print "$_=$tcp_count{$_}\n";
}

# Print UDP stats
foreach(keys(%udp_count))
{
	print "$_=$udp_count{$_}\n";
}

exit(0);
