Created
November 29, 2012 07:11
-
-
Save bitfolk/4167319 to your computer and use it in GitHub Desktop.
Convert an IPv6 CIDR format address to its corresponding reverse zone
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/perl | |
use strict; | |
use warnings; | |
foreach my $cidr (qw(2001:ba8:1f1:f004::/64 4:2::/32 2001:ba8:1f1:400::/56)) { | |
print "$cidr reverses to ", v6_cidr_to_reverse($cidr), "\n"; | |
} | |
sub v6_cidr_to_reverse | |
{ | |
my ($cidr) = @_; | |
my ($prefix, $net_bits) = split(/\//, $cidr); | |
# Bust the v6 address apart into the colon-delimited sections. | |
my @sections = split(/:/, $prefix); | |
my @v6_array; | |
# Iterate through them backwards. | |
foreach my $section (reverse @sections) { | |
# Split each section up backwards into a list, so e.g. '2001' becomes | |
# ('1', '0', '0', '2'). | |
my @digits = reverse(split(//, $section)); | |
my $str = $digits[0]; | |
my $i; | |
# Join the digits we have together with dots. | |
for ($i = 1; $i <= $#digits; $i++) { | |
$str .= ('.' . $digits[$i]); | |
} | |
# If there were fewer than four digits then make the remainder up with | |
# zeroes. | |
while ($i < 4) { | |
$str .= '.' . '0'; | |
$i++; | |
} | |
push(@v6_array, $str); | |
} | |
# Join the sections together with dots and add the reverse zone TLD on the | |
# end. | |
my $revstr = join('.', @v6_array) . '.ip6.arpa'; | |
my $have_bits = 16 * scalar @v6_array; | |
if ($have_bits > $net_bits) { | |
# They gave us a prefix like 2001:ba8:1f1:400::/56 which specifies 64 | |
# bits, not 56, so we have to chop off the first few nibbles. | |
# Multiply by 2 because we need to remove the dots as well! | |
my $remainder = ($have_bits - $net_bits) / 4 * 2; | |
$revstr =~ s/^[0-9a-f\.]{$remainder}//; | |
} elsif ($net_bits > $have_bits) { | |
# They didn't specify a big enough prefix, e.g. | |
# 2001:ba8:1f1::/56 which specifies 48 bits, not 56, so | |
# we have to front pad with zeroes. | |
my $remainder = ($net_bits - $have_bits) / 4; | |
$revstr = '0.' x $remainder . $revstr; | |
} | |
return $revstr; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
As David points out,
Net::IP
can do this:http://strugglers.net/~andy/blog/2012/11/29/converting-an-ipv6-address-to-its-reverse-zone-in-perl/comment-page-1/#comment-273999