Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re: Quickly determine which IP range an IP belongs to. (two keys)

by tye (Sage)
on Nov 30, 2010 at 05:40 UTC ( [id://874427]=note: print w/replies, xml ) Need Help??


in reply to Quickly determine which IP range an IP belongs to.

The route I recently went that worked well for the mix of IPv4 addresses and ranges that I had was to, for IPv4 addresses, just use the IP address as a hash key. For IP ranges, I used the first 3 octets of the range as the hash key and the value was a list of ranges that I looped through (it was rare that I had more than one range having the same first three octets). I didn't have any ranges that covered more than one three-octet block, but if I had, I would split such ranges up.

my %hash= ( '127.0.0.1' => 'localhost', '10.11.12.1' => 'router', '10.11.12.10' => 'desktop', '10.11.12.' => [ { min => 101, max => 120, desc => 'printers' }, { min => 250, max => 254, desc => 'tanks' }, ], ); sub findIP { my( $ip )= @_; my $desc= $hash{$ip}; return( $ip, $desc ) if $desc; my( $last )= $ip =~ s/(\d+)$//; my $ranges= $hash{$ip}; for my $range ( @{ $ranges || [] } ) { my( $min, $max )= @$range{'min','max'}; return( "$ip.$min-$max", $range->{desc} ) if $min <= $last && $last <= $max; } return; }

- tye        

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://874427]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (2)
As of 2024-04-26 04:19 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found