package IP_iterator;
$VERSION = "0.1";

# constructor: parses the given network specification and sets range variables.
sub new {
  my ($type, $netspec) = @_;
  my $self = [];
  bless($self, $type);

  my @ip = split /\./, $netspec;
  for (my $i = 0; $i <= 3; $i++) {
    my $ipp = $ip[$i];

    if ($ipp eq '*') {		# wildcard
      $self->[$i] = {
		     from  => 0,
		     to    => 255,
		     count => 0
		    }
    } elsif ($ipp =~ /^([0-9]+)-([0-9]+)$/) { # range
      $self->[$i] = {
		     from  => $1,
		     to    => $2,
		     count => $1
		    }
    } elsif ($ipp =~ /^([0-9]+)$/) { # number
      $self->[$i] = {
		     from  => $1,
		     to    => $1,
		     count => $1
		    }
    }
  }
  $self->[4] = 0;		# the "last"-flag

  return $self;
}


# returns actual ip and increments. If all ip's are iterated, this returns an undefined value.
sub next {
  my ($self) = @_;

  my $ip = $self->[4] == 0 ? $self->[0]{count}.".".$self->[1]{count}.".".$self->[2]{count}.".".$self->[3]{count} : return undef;

  my $ovfl = 1;
  for (my $i = 3; $i >= 0; $i--) {
    if ($ovfl == 0) {
      last;
    }
    $ovfl = 0;
    if (++$self->[$i]{count} > $self->[$i]{to}) { $ovfl = 1; $self->[$i]{count} = $self->[$i]{from}}
  }
  $self->[4] = $ovfl;

  return $ip;
}
