[Za-pm] IP's
Oskar Pearson
oskar at qualica.com
Thu May 6 06:47:41 CDT 2004
Hi
> Any body got any cool code to check if an IP is within a particular range?
> I can check the four individual elements of the code with a series of if
> statements but there must be a more graceful way to do it.
>
> if 196.2.49.19 is in the range 196.2.1.1 to 196.3.29.76 do something.
You could convert it all to the numeric representation of the
IP and do a simple "less than or greater than" trick.
#!/usr/bin/perl -w
use strict;
my $ip = "196.2.49.19";
my $startRange = "196.2.1.1";
my $endRange = "196.3.29.76";
my $ip_num = &numeric($ip);
my $startRange_num = &numeric($startRange);
my $endRange_num = &numeric($endRange);
unless($startRange_num < $endRange_num) {
die("Start of range is not less than end of range");
}
if (($ip_num >= $startRange_num) && ($ip_num <= $endRange_num)) {
print "Is in range ($ip_num, $startRange_num, $endRange_num)\n";
} else {
print "Is NOT range ($ip_num, $startRange_num, $endRange_num)\n";
}
sub numeric {
my $ip = shift;
unless ($ip =~ /^([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)$/) {
die("Ip invalid? $ip");
}
my $numeric;
$numeric = $1 * 256 * 256 * 256;
$numeric += $2 * 256 * 256;
$numeric += $3 * 256;
$numeric += $4;
#print "Numeric: $numeric\n";
return($numeric);
}
Says:
Is in range (3288477971, 3288465665, 3288538444)
Oskar
--
Oskar Pearson <oskar at qualica.com>
Qualica Technologies (Pty) Ltd
web: http://www.qualica.com/
More information about the Za-pm
mailing list