#!/usr/bin/perl

# Copyright (C) 2010 Andrea Martire
# 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 (at your option) 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.

sub dec2bin {
    my $str = unpack("B32", pack("N", shift));
    #$str =~ s/^0+(?=\d)//;   # delete leading zeros
    return $str;
}

sub bin2dec {
    return unpack("N", pack("B32", substr("0" x 32 . shift, -32)));
}

sub IPnumber {
	$var = $_[0];
    if( $var =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/ ) {
		return &dec2bin($1 << 24 | $2 << 16 | $3 << 8 | $4);
	}
}

sub IPmask {
	$var = $_[0];
    return &dec2bin(-1<<(32-$var));
}

sub ipMatchNet  {
	$ip = &IPnumber($_[0]);
	print "IP\t$ip\n";
	$mask = &IPmask($_[2]);
	print "MASK\t$mask\n";
	$ipnet = $ip & $mask;
	print "IP NET\t$ipnet\n";
	$net = &IPnumber($_[1]);
	print "NET\t$net\n";

	if( ($ip & $mask) eq $net ) {
		return 1;
	}
	return 0;
}

1;
