Skip to content

Instantly share code, notes, and snippets.

@inopinatus
Created July 5, 2012 06:49
Show Gist options
  • Save inopinatus/3051890 to your computer and use it in GitHub Desktop.
Save inopinatus/3051890 to your computer and use it in GitHub Desktop.
prefix test
#!/usr/bin/perl
use strict;
use integer;
sub dqtoint ($) {
my $dq = shift;
return unpack('N', pack('CCCC', split(/\./, $dq, 4)));
}
sub inttodq ($) {
my $i = shift;
return join('.', unpack('CCCC', pack('N', $i)));
}
sub shortestboundary ($) {
my $i = shift;
my $mask = (2**32) -1; # 1<<32 doesn't work
my $shift = 0;
while ($i) {
$i = ($i << 1) & $mask;
$shift++;
}
return $shift;
}
sub prefixtonum ($) {
my $p = shift;
my ($prefix, $len, $int, $lowint, $size, $highint, $boundary, $isguess);
($prefix) = $p =~ m,^([0-9.]+)/?,;
($len) = $p =~ m,/(\d+)$,;
$int = dqtoint($prefix);
$boundary = shortestboundary($int);
if ($isguess = not defined $len) {
$len = $boundary;
}
$size = (1<<(32-$len)) - 1;
$lowint = $int & ~$size;
$highint = $lowint + $size;
if ($int == $lowint) {
print "$prefix/$len equals inetnum ", inttodq($lowint), " - ", inttodq($highint), "\n";
} else {
print "$prefix/$len is in inetnum ", inttodq($lowint), " - ", inttodq($highint), "\n";
}
print "(using guess of $boundary for prefix-length)\n" if $isguess;
unless ($len == $boundary) {
my $bsize = (1<<(32-$boundary)) -1;
my $blow = $int & ~$bsize;
my $bhigh = $blow + $bsize;
print "(shortest length $boundary, inetnum ", inttodq($blow), " - ", inttodq($bhigh), ")\n";
}
}
while (defined (my $subnet = shift)) {
chomp $subnet;
prefixtonum($subnet);
print "\n" if @ARGV;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment