You could try NetAddr::IP:
use strict; use warnings; use Test::More; use NetAddr::IP; my @routes = ( [ qw(192.168.0.0/24 192.168.0.1) ], [ qw(10.10.10.0/24 10.10.10.1) ], [ qw(12.162.8.11/28 default) ], ); is( calc_route( "192.168.0.88" ), "192.168.0.1", "first route" ); is( calc_route( "192.168.1.88" ), "default", "close to first rout +e but default" ); is( calc_route( "10.10.10.12" ), "10.10.10.1", "second route (examp +le IP)" ); is( calc_route( "12.162.8.3" ), "default", "explicit default" ) +; is( calc_route( "1.2.3.4" ), "default", "else: default" ); done_testing; sub calc_route { my $ip = NetAddr::IP->new( shift ); for my $test_subnet ( @routes ) { if ( $ip->within( NetAddr::IP->new( $test_subnet->[0] ) ) ) { return $test_subnet->[1]; } } return 'default'; }
Result:
ok 1 - first route ok 2 - close to first route but default ok 3 - second route (example IP) ok 4 - explicit default ok 5 - else: default 1..5
Use hashes and pre-computed objects for better performance (left as an exercise ;-).
In reply to Re: Determine which route to take
by Perlbotics
in thread Determine which route to take
by mhearse
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |