Reputation: 375
I have to iterate through a range of ip addresses in perl and print a list of all ip's in that range. for ex - for
192.168.122.1-192.168.122.4
My return value is
192.168.122.1, 192.168.122.2, 192.168.122.3, 192.168.122.4
Also I cannot use Net::IP
or Netmask
modules, so finding other ways to iterate.
Following solution works but has some problems i cant seem to figure out -
1 - my start and end would be perl variables "" and not as mentioned in the code below. The code below doesnt work with start="192.168.122.1"
2 - How can i get a list of all ips appended at the end?
sub inc_ip { $_[0] = pack "N", 1 + unpack "N", $_[0] }
my $start = 192.168.122.1;
my $end = 192.168.122.4;
for ( $ip = $start; $ip le $end; inc_ip($ip) ) {
printf "%vd\n", $ip;
}
Upvotes: 1
Views: 1290
Reputation: 25153
Use Net::IP. From the CPAN documentation:
use Net::IP;
my $ip = new Net::IP ('195.45.6.7 - 195.45.6.19') || die;
# Loop
do {
print $ip->ip(), "\n";
} while (++$ip);
This approach is more flexible because Net::IP accepts CIDR notation e.g. 193.0.1/24 and also supports IPv6.
Upvotes: 1
Reputation: 8972
You seem to want:
use Socket 'inet_aton';
my $start = "192.168.122.1";
my $end = "192.168.122.4";
my @x = map { sprintf "%vi", pack "N", $_ } unpack("N",inet_aton($start)) .. unpack("N",inet_aton($end));
use DDP; p @x;
Upvotes: 0