Showing posts with label Perl. Show all posts
Showing posts with label Perl. Show all posts

Saturday, March 31, 2012

Convert an IP Address Range into CIDR Notation

While looking for a way to convert a range of IP addresses to CIDR notation, I came across a really neat Perl module on CPAN. It is called Net::CIDR.

Among other thigs, the module converts IP addressed given as a range such as 216.117.192.0 - 216.117.223.255 into CIDR notation:

216.117.192.0/19

It even works if the address range is not a single block (quite common with the whois servers run by spam friendly ISP's). For example 216.117.192.0 - 216.117.254.255 converts to:

216.117.192.0/19
216.117.224.0/20
216.117.240.0/21
216.117.248.0/22
216.117.252.0/23
216.117.254.0/24


#!/usr/bin/perl
use strict;
use warnings;

use Net::CIDR;

# snarf lines from STDIN
my @rlist = ();
foreach my $line (<STDIN>) {
  chomp $line;
  next unless $line;
  
  push @rlist,$line;
}

# convert to CIDR notation
foreach my $line (Net::CIDR::range2cidr(@rlist)) {
  print $line . "\n";
}

If you want the output sorted by IP address pipe the output from the above program through the sort command:

sort -n -t '.' -k 1,1 -k 2,2 -k 3,3 -k 4,4