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 - into CIDR notation:

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 - converts to:

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

1 comment:

  1. this code just hangs....can you post an example run. I've tried various things and all it does is hang


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.