Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
#!/usr/bin/perl -w
use Net::CIDR;
use Getopt::Long;
# Net::CIDR one liner:
# perl -mNet::CIDR -ne 'print if Net::CIDR::cidrlookup($_, ("10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16"))'
#
# TODO: add ip address validation
sub usage {
my $name = $0;
$name =~ s/.*\///;
print <<EOT;
Usage: $name [options] ip1 [ip2 ip3 ...]
Print ip addresses that belong to RFC1918 private address blocks.
Read ip numbers on the command line or from standard in.
Options:
-h, --help: print this message
-n, --not: print non-private ip addresses
EOT
}
sub filter_ip {
my ($ip) = @_;
print $ip, "\n" if Net::CIDR::cidrlookup($ip, @rfc1918_blocks) ^ $not;
}
BEGIN {
my $help;
our $not = 0;
our @rfc1918_blocks = ('10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16');
GetOptions(
'help' => \$help,
'h' => \$help,
'not!' => \$not,
);
defined $help and usage() and exit;
}
if ($#ARGV > -1) {
while ($#ARGV > -1) { # process every ip address on the command line
filter_ip($ARGV[0]);
shift;
}
} else {
while (<>) { # read from standard in if there's nothing on the command line
chomp;
filter_ip($_);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment