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

No comments:

Post a Comment

Off topic comments will be deleted. Comments with spelling or grammar errors may be deleted unless they have hoplophobic or statist content in which case they will be highlighted and ridiculed.

Note: Only a member of this blog may post a comment.