adismaug has asked for the wisdom of the Perl Monks concerning the following question:

Dear monks,
I need to create a tool which will get, as an input, IP prefixes from a routing table, like this:
10.1.1.0/24
10.1.0.0/16
10.1.2.0/24
10.1.0.0/20
10.1.1.1/32
10.224.224.0/23
And find prefixes which are related and print the longest one (not the most specific as router do).
I tried many modules but failed to do that.
Regards,
Adi.

Replies are listed 'Best First'.
Re: IP prefix match
by jethro (Monsignor) on Jul 06, 2009 at 13:19 UTC

    You could translate the addresses to binary cut off at the end of the prefix, i.e. '10.1.0.0/16' becomes 0000101000000001, then just compare all binary strings in the list if they begin with any binary string of the list that is shorter. If yes, this prefix is part of the prefix of the shorter string