#!/usr/bin/perl

# WHAT THIS DOES
#   Given a list of CIDR notation IP addresses and ranges
#   compact them and spit them out in tcprules-friendly
#   format to stdout

# USAGE
#   ./CIDR2tcprules.pl [file1] [file2 ... ] 
#      if a filename is omitted, stdin is read instead

# CAVEATS
#   any whitespace at the end of any line is removed, permanently
#   the entire list is read into an array, processed into another, and then another,
#      and then printed.  If you have a LOT of lines this may take quite a bit of
#      time and memory.

# REQUIREMENTS
#   perl - duh!
#   NetAddr::IP perl module.
#   anything required by the above two requirements, including perl version.
#   list of CIDR notation IP addresses and ranges.  Script is useless without this :)

# AUTHOR: Jeremy Kitchen - kitchen@scriptkitchen.com 8/6/2004

# THIS PROGRAM COMES WITH NO WARRANTY.  IF YOU SCREW UP SOME FILE(S)
# AFTER USING IT, DAMN, YOU'RE SCREWED.

use strict;
use NetAddr::IP qw/Compact/;
my @addresses;

# read in the addresses.
while (<>) {
	chomp;
	s/\s*$//;
	push @addresses, NetAddr::IP->new($_);
}

# store the compacted list into a new array
my @compacted = Compact(@addresses);
my @nprefix;

# convert to tcpserver-style format
foreach (@compacted) {
	push @nprefix, $_->nprefix;
}

# print them all out
print join("\n", @nprefix) . "\n";


# THANKS
#   Google for finding me the module to do this
#   http://mipagina.cantv.net/lem/perl/iptut.htm for the wonderful examples
#   Luis Muņoz for the perl module (also the author of the above URL)
#   Dave Horton for making me need this script ;)
#   Chris Huseman for telling me to write it ;)
