Skip to content

Instantly share code, notes, and snippets.

@putnamhill
Last active December 14, 2017 15:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save putnamhill/23b6b24288a20bca57fdb4a9895c3fb9 to your computer and use it in GitHub Desktop.
Save putnamhill/23b6b24288a20bca57fdb4a9895c3fb9 to your computer and use it in GitHub Desktop.
Reads ip addresses from the command line or stdin and prints them if they belong to any of the three RFC1918 private address blocks
#!/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