in reply to IP Iterator

IPv4 addresses are 32-bit numbers. Thinking of them as 4 individual bytes is counter-productive and leads to extremely convoluted code. nextIP should be:

sub nextIP { my ($ip) = @_; return $ip+1; }

exit shouldn't be called from nextIP. That's a user-interface detail while nextIP is clearly not an I/O function. A wrap can be detected by nextIP returning 0.

Replies are listed 'Best First'.
Re^2: IP Iterator
by camlet (Novice) on Apr 17, 2008 at 15:50 UTC
    3) yes this works well thank you. it makes sense but to think as 32bit rather than 4 individual byte. change made. still testing the code.
      sub nextIP { my ($ip) = @_; return $ip+1; } didnt work the user doesnt enter binary it still needs to be transformed with if.

        Nope. All you need is the following:

        sub ip_fr_dotted { unpack 'N', pack 'C4', split /\./, $_[0] } sub ip_to_dotted { join '.', unpack 'C4', pack 'N', $_[0] } my $start = ip_fr_dotted('10.0.0.0'); my $end = ip_fr_dotted('10.0.0.255'); for (my $ip=$start; $ip<=$end; $ip++) { print(ip_to_dotted($ip), "\n"); }

        I didn't use for my $ip ($start..$end) since it doesn't work for IP addresses ≥ 128.0.0.0 on a 32-bit system.

        your recommeded solution worked also for subnet level increases. thank you. making the change now.
        10.0.1.252 10.0.1.253 10.0.1.254 10.0.1.255 10.0.2.0 10.0.2.1 10.0.2.2 10.0.2.3 10.0.2.4 10.0.2.5
        script:
        sub ip_fr_dotted { unpack 'N', pack 'C4', split /\./, $_[0] } sub ip_to_dotted { join '.', unpack 'C4', pack 'N', $_[0] } my $start = ip_fr_dotted('10.0.0.200'); my $end = ip_fr_dotted('10.0.2.23'); for (my $ip=$start; $ip<=$end; $ip++) { print(ip_to_dotted($ip), "\n"); }