#!/usr/bin/perl -w use strict; use warnings; my @tests; BEGIN { @tests = ( [ '10.1.2.31', '10.1.2.30', '10.1.2.45' , 1 ], [ '10.1.2.255', '9.1.2.30', '11.1.2.45' , 1 ], [ '10.1.2.255', '10.1.1.30', '10.1.3.45' , 1 ], [ '10.1.2.255', '10.1.2.30', '10.1.2.45' , 0 ], [ '10.1.2.255', '10.1.2.30', '10.1.2.255', 1 ], [ '10.1.2.29', '10.1.2.30', '10.1.2.255', 0 ], [ '10.1.2.30', '10.1.2.30', '10.1.2.255', 1 ], ); } use Test::More tests => 14+1; for my $check ( @tests ) { my( $test, $start, $end, $result ) = @{ $check }; my $desc = "$test " . ( $result ? "is" : "isn't" ) . " between $start and $end"; is( ip_in_range( $test, $start, $end), $result, $desc ); is( cmp_ips( $test, $start, $end), $result, $desc ); } is( ip_in_range( "I R BAD IP", "10.2.1.1", "10.2.1.10" ), undef, "Bad IP Check" ); ## 13 lines use Socket qw( inet_aton ); sub ip_in_range { my ( $test, $start, $end ) = map { unpack( "N", inet_aton($_) ) or do { warn "Invalid IP: $_\n"; return undef } } @_; return 0 if $test < $start; return 0 if $test > $end; return 1; } ## 27 lines sub cmp_ips{ my @r; my @t = quadify(shift); my @s = quadify(shift); my @e = quadify(shift); ($t[0] == $s[0] && $t[0] == $e[0]) ? $r[0] = 1 : $r[0] = 0; ($t[1] == $s[1] && $t[1] == $e[1]) ? $r[1] = 1 : $r[1] = 0; ($t[2] == $s[2] && $t[2] == $e[2]) ? $r[2] = 1 : $r[2] = 0; ($t[3] == $s[3] && $t[3] == $e[3]) ? $r[3] = 1 : $r[3] = 0; return 1 if $t[0]*$t[1]*$t[2]*$t[3] == 1; return 1 if ($r[0] == 0 && ($t[0] >= $s[0] && $t[0] <= $e[0]) ); return 1 if ($r[1] == 0 && ($t[1] >= $s[1] && $t[1] <= $e[1]) ); return 1 if ($r[2] == 0 && ($t[2] >= $s[2] && $t[2] <= $e[2]) ); return 1 if ($r[3] == 0 && ($t[3] >= $s[3] && $t[3] <= $e[3]) ); return 0; } sub quadify{ my $ip = shift; $ip =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/; return ($1,$2,$3,$4); } __END__ 1..15 ok 1 - 10.1.2.31 is between 10.1.2.30 and 10.1.2.45 ok 2 - 10.1.2.31 is between 10.1.2.30 and 10.1.2.45 ok 3 - 10.1.2.255 is between 9.1.2.30 and 11.1.2.45 ok 4 - 10.1.2.255 is between 9.1.2.30 and 11.1.2.45 ok 5 - 10.1.2.255 is between 10.1.1.30 and 10.1.3.45 ok 6 - 10.1.2.255 is between 10.1.1.30 and 10.1.3.45 ok 7 - 10.1.2.255 isn't between 10.1.2.30 and 10.1.2.45 not ok 8 - 10.1.2.255 isn't between 10.1.2.30 and 10.1.2.45 # Failed test '10.1.2.255 isn't between 10.1.2.30 and 10.1.2.45' # in /Users/fletch/snit at line 26. # got: '1' # expected: '0' ok 9 - 10.1.2.255 is between 10.1.2.30 and 10.1.2.255 ok 10 - 10.1.2.255 is between 10.1.2.30 and 10.1.2.255 ok 11 - 10.1.2.29 isn't between 10.1.2.30 and 10.1.2.255 not ok 12 - 10.1.2.29 isn't between 10.1.2.30 and 10.1.2.255 # Failed test '10.1.2.29 isn't between 10.1.2.30 and 10.1.2.255' # in /Users/fletch/snit at line 26. # got: '1' # expected: '0' ok 13 - 10.1.2.30 is between 10.1.2.30 and 10.1.2.255 ok 14 - 10.1.2.30 is between 10.1.2.30 and 10.1.2.255 Use of uninitialized value in unpack at /Users/fletch/snit line 34. Invalid IP: I R BAD IP ok 15 - Bad IP Check # Looks like you failed 2 tests of 15.