-2

I've been looking for a way to iterate through Ip range and I come across this response

sub inc_ip { $_[0] = pack "N", 1 + unpack "N", $_[0] }
my $start = 1.1.1.1;
my $end = 1.10.20.30;
for ( $ip = $start; $ip le $end; inc_ip($ip) ) {
    printf "%vd\n", $ip;
}

What I want to knew is if there is a way to convert string like my $start = "192.168.1.1"; to vector flag. What I get when I pass a string is some random numbers

Mobrine Hayde
  • 365
  • 1
  • 2
  • 10

1 Answers1

3
pack 'C*', split /\./, $s

Or for IPv4 specifically,

use Socket qw( inet_aton );

inet_aton($s)

For example, you could use

use Socket qw( inet_aton );

my $start = unpack('N', inet_aton('1.1.1.1'));
my $end   = unpack('N', inet_aton('1.10.20.30'));

for my $ip ($start..$end) {
   printf("%vd\n", pack('N', $ip));
}
ikegami
  • 367,544
  • 15
  • 269
  • 518