How can I generate a range of IP addresses in Perl?

会有一股神秘感。 提交于 2019-11-28 00:28:44

问题


I need to generate a list of IP-addresses (IPv4) in Perl. I have start and end addresses, for example 1.1.1.1 and 1.10.20.30. How can I print all the addresses inbetween?


回答1:


Use Net::IP's looping feature:

The + operator is overloaded in order to allow looping though a whole range of IP addresses:




回答2:


Use Net::IP. From the CPAN documentation:

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.

Edit: if you are working with netblocks specifically, you might investigate Net::Netmask.




回答3:


It's all in how you code it. This is the fastest way I know.

my $start = 0x010101; # 1.1.1
my $end   = 0x0a141e; # 10.20.30

for my $ip ( $start..$end ) { 
    my @ip = ( $ip >> 16 & 0xff
             , $ip >>  8 & 0xff
             , $ip       & 0xff
             );
    print join( '.', 1, @ip ), "\n";
}



回答4:


TMTOWTDI:

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;
}



回答5:


# We can use below code to generate IP range

use warnings;
use strict;
my $startIp = $ARGV[0];
my $endIp = $ARGV[1];
sub range {
my (@ip,@newIp,$i,$newIp,$j,$k,$l,$fh);
my ($j1,$k1,$l1);
open($fh,">","ip.txt") or die "could not open the file $!";
@ip = split(/\./,$startIp);
for($i=$ip[0];$i<=255;$i++) {
  for($j=$ip[1];$j<=255;$j++) {
    $ip[1]=0 if($j == 255);
     for($k=$ip[2];$k<=255;$k++) {
        $ip[2]=0 if($k == 255);
        for($l=$ip[3];$l<=255;$l++) {
            $ip[3]=0 if($l == 255);
            @newIp = $newIp = join('.',$i,$j,$k,$l);
            print $fh "$newIp \n";
            exit if ($newIp eq $endIp);
        }
      }
    }
  }
}
range ($startIp, $endIp);


来源:https://stackoverflow.com/questions/2279756/how-can-i-generate-a-range-of-ip-addresses-in-perl

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!