#!/usr/bin/perl -w
#
# __copy1__
# __copy2__
#
my $CMD		= "ipmatch";
my $CMDVERSION	= "1.0 (2015/08)";
my $VERBOSE	= 0;

use Net::IP::Match::Regexp qw( create_iprange_regexp match_ip );

if (defined $ARGV[0]) {
	if ($ARGV[0] eq "-v" || $ARGV[0] eq "--verbose") {
		$VERBOSE = 1;
		shift( @ARGV );
	}
}
if (defined $ARGV[0]) {
	if ($ARGV[0] eq "-h" || $ARGV[0] eq "--help") {
		print_help();
		exit( 0 );
	}
}
if (defined $ARGV[0]) {
	if ($ARGV[0] eq "-V" || $ARGV[0] eq "--version") {
		print( "$CMD $CMDVERSION\n" );
		exit( 0 );
	}
}

usage()	if (scalar(@ARGV) < 2);

my $ip		= shift( @ARGV );
my @networks;
my $status	= 0;
my $net;

foreach $net (@ARGV) {
	if ($net !~ /\//) {
		if ($net =~ /\.0$/) {
			$net .= "/24";
		} else {
			$net .= "/32";
		}
	}
	push( @networks, { $net => $net } );
}

my $regexp	= create_iprange_regexp( @networks );
my $out		= match_ip( $ip, $regexp );

if ($out) {
	printf( "%s MATCH %s\n", $ip, $out ) 	if ($VERBOSE);
} else {
	printf( "%s no match\n", $ip )	if ($VERBOSE);
	$status = 1;
}

exit( $status );




sub usage
{
	die( "
usage:	$CMD ip network(s)
	$CMD -v|--verbose
	$CMD -V|--version
	$CMD -h|--help
" );
}

sub print_help
{
	printf( STDERR "
$CMD - $CMDVERSION

checks if an ip belongs to a network from a given list

networks should be listed as complete CIDR notation, eg 10.1.2.0/24;
if you omit the mask part, it will be set to /24 (if last number is .0)
or /32 otherwise
" );
}

