Wednesday, March 28, 2007

Code to decode an a.b.c.d/n IP address range to the list of IP addresses

I needed to map some addresses in the standard IP address prefix syntax to the actual list of addresses, and after I'd searched Google for all of 11 usecs for a suitable on-line decoder I hacked one up in Perl.

Since someone else might find this handy, here it is:

use strict;
use warnings;

my $address = $ARGV[0] || '/';

my ( $ip, $bits ) = split( /\//, $address );
my @octets = split( /\./, $ip );

if ( ( $address eq '' ) ||
( $bits eq '' ) ||
( $#octets != 3 ) ) {
die "Usage: ip-decode a.b.c.d/x\n";
}

my $base = ( ( $octets[0] * 256 + $octets[1] ) * 256 +
$octets[2] ) * 256 + $octets[3];

my $remaining = 32 - $bits;

for my $i (0..(2 ** $remaining) - 1) {
print_ip( $base + $i );
}

sub print_ip
{
my ( $address ) = @_;

my @octets;

for my $i (0..3) {
push @octets, ($address % 256);
$address >>= 8;
}

print "$octets[3].$octets[2].$octets[1].$octets[0]\n";
}

For example, if this script is called ip-decode and you want to decode the address prefix 82.15.171.152/29 you type ip-decode 82.15.171.152/29 and you'll get the output:

82.15.171.152
82.15.171.153
82.15.171.154
82.15.171.155
82.15.171.156
82.15.171.157
82.15.171.158
82.15.171.159

This script has undergone no testing at all...

No comments: