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
|
|---|