Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: Determine which route to take

by Perlbotics (Archbishop)
on Aug 02, 2013 at 22:52 UTC ( [id://1047662]=note: print w/replies, xml ) Need Help??


in reply to Determine which route to take

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 ;-).

Replies are listed 'Best First'.
Re^2: Determine which route to take
by mhearse (Chaplain) on Aug 03, 2013 at 00:30 UTC
    Thanks for your reply. For some reason I though it would be a simple bitwise AND. My knowledge of bitwise operators is pathetic.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others having a coffee break in the Monastery: (4)
As of 2024-04-23 15:19 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found