On Thu, Nov 27, 2008 at 00:02, Chas. Owens <[EMAIL PROTECTED]> wrote:
snip
>>> Now I need to map C_IP to list with longest prefix match. (As u can
>>> there are many IP address with 12.120. but I need to map to one with
>>> longest prefix match)
>>
>> The algorithm/data structure you are looking for is called a trie*.
>> There are a few modules on CPAN that seem to implement tries for you:
>> Data::Trie**, Tree::Trie***, Net::IPTrie****.  Off hand, I would say
>> Net::IPTrie looks like what you need.
snip
> It looks like it is fairly easy as well, but I haven't checked to see
> if 12.120.24.0|21 is the right answer:
snip

Given a simple set of address spaces it looks like it is returning the
answers you want:

10.0.0.0 is in 10.0.0.0|32
10.0.0.1 is in 10.0.0.0|24
10.0.1.0 is in 10.0.0.0|16
10.1.0.0 is in 10.0.0.0|8
11.0.0.0 is in not found

#!/usr/bin/perl

use strict;
use warnings;

use Net::IPTrie;

my $tr = Net::IPTrie->new(version => 4);
for my $data (qw/10.0.0.0|8 10.0.0.0|16 10.0.0.0|24 10.0.0.0|32/) {
        my ($ip, $prefix) = split /\|/, $data;
        $tr->add(address => $ip, prefix => $prefix, data => $data);
}

for my $ip (qw/10.0.0.0 10.0.0.1 10.0.1.0 10.1.0.0 11.0.0.0/) {
        my $match = $tr->find(address => $ip);
        print "$ip is in ", defined $match ? $match->data : "not found", "\n";
}


-- 
Chas. Owens
wonkden.net
The most important skill a programmer can have is the ability to read.

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to