in reply to Determine which route to take
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
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: Determine which route to take
by mhearse (Chaplain) on Aug 07, 2013 at 16:12 UTC | |
by rjt (Curate) on Aug 07, 2013 at 17:49 UTC |
In Section
Seekers of Perl Wisdom