Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

I'd use a module, too, but if you want/need to know how the math works, it's actually pretty simple:

Update: Add this summary of the math:

Convert IP address (or route subnet) to integer:

my $ip = ($A << 24) + ($B << 16) + ($C << 8) + $D; # Do the same for each route address ($net)

Convert /24 CIDR notation to 0xffffff00 netmask:

    my $mask = 0xffffffff ^ (1 << 32 - $cidr) - 1;

Check if a destination IP matches a route:

    ($ip & $mask) == $net;

Full example:

#!/usr/bin/env perl use 5.012; use warnings FATAL => 'all'; # Use an array instead if order is important my %routes = ( '192.168.0.1' => [ '192.168.0.0' => 24 ], '10.10.10.1' => [ '10.10.10.0' => 24 ], 'default' => [ '12.162.8.11' => 28 ], ); printf "%15s -> %s\n", $_, route($_) for qw< 10.10.10.12 128.127.126.125 192.168.0.51 192.168.1.1 10.10.10.5 >; sub ip { $_[0] =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/ or die "Invalid IP"; die "Octet out of range" if ($1 & $2 & $3 & $4) > 255; ($1 << 24) + ($2 << 16) + ($3 << 8) + $4 } sub route { my $ip = ip($_[0]); while (my ($dest, $route) = each %routes) { my ($net, $cidr) = @$route; my $mask = 0xffffffff ^ (1 << 32 - $cidr) - 1; return $dest if ($ip & $mask) == ip($net); } return 'default'; }

Output:

10.10.10.12 -> 10.10.10.1 128.127.126.125 -> default 192.168.0.51 -> 192.168.0.1 192.168.1.1 -> default 10.10.10.5 -> 10.10.10.1

In reply to Re: Determine which route to take by rjt
in thread Determine which route to take by mhearse

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others learning in the Monastery: (3)
As of 2024-04-25 19:16 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found