The code looks something like this:12.34.56.78/16|City A 90.12.34.56/19|City B etc
Then to check which city an ip address belongs in, I just do a sequential search:# Build an array. Each element of the array is a reference # to a two-element array consisting of a Net::Netmask object # and a city name my @blocks; while (<FH>) { my ($block, $city) = split /\|/; push @blocks, [Net::Netmask->new($block), $city]; }
The code could be written faster by using a better search algorithm [1], but a sequential search of my company's 2100+ netblocks takes negligible time so I haven't seen fit to recode it.sub find_city { my $address = shift; foreach my $arrayref (@blocks) { # Extra variables assigned for clarity my $netblock = $arrayref->[0]; my $city = $arrayref->[1]; if ($netblock->match($address)) { return $city; } } }
[1] We don't have anything larger than a /16, so hash buckets keyed on the first two octets could speed things up a bit. Something like this:
$blocks{10}{0} = [ [Net::Netmask->new("10.0.0.0/24"), "City A"], [Net::Netmask->new("10.0.1.0/24"), "City B"] ]; $blocks{10}{1} = [ [Net::Netmask->new("10.1.0.0/24"), "City C"], [Net::Netmask->new("10.1.1.0/24"), "City D"] ];
-Matt
In reply to Re: Best structure for range find?
by DrManhattan
in thread Best structure for range find?
by Jykke
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |