#!/usr/bin/perl
# $Id: subnet2ip.pl,v 1.2 2002/02/21 16:09:20 gadsden Exp $
#
# Program to read list of subnets in CIDR format from stdin and write the
# list of all IP addresses in those subnets on stdout. Output will not
# include broadcast addresses unless -b flag is given on command line.
#
# Author: Richard Gadsden <gadsden@musc.edu>
#         Medical University of South Carolina
#         Charleston, SC, USA

use Getopt::Std;

getopts ('b');
if (defined ($opt_b)) { $BROADCAST = 1; }

while (<>) {
  chop;
  ($addr, $netbits) = split(/\//);
  $hostbits = 32 - $netbits;
  $netsize = 2**$hostbits;
  for ($i = 0 ; $i < $netsize - 1 ; $i++) {
    print &stepaddr ($addr, $i), "\n";
  }
  if ($BROADCAST) { print &stepaddr ($addr, $netsize - 1), "\n"; }
}

sub stepaddr {
  local ($addr, $i) = @_;
  @octet = split(/\./, $addr);
  $octet[3] += $i;
  for (local $j = 3 ; $j > 0 ; $j--) {
    if ($octet[$j] >= 256) { 
      $octet[$j-1] += int ($octet[$j]/256);
      $octet[$j] %= 256; 
    }
  }
  return join (".", @octet);
}
