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":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.