I'm a big fan of Net::Netmask. I maintain a simple database of my company's netblocks and which city they belong in by building an array of Net::Netmask/city combinations. Assuming the netblocks/cities are stored in a pipe-delimited text file like so:
12.34.56.78/16|City A 90.12.34.56/19|City B etc
The code looks something like this:
# 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]; }
Then to check which city an ip address belongs in, I just do a sequential search:
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; } } }
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.

[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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.