在工作中通常需要将类似“192.168.1.0/24”的IP转换为“192.168.1.0~192.168.1.255”的格式。如果需要转换的IP地址段比较多,且子网掩码各不一样,那么手动换算工作量比较大,也容易出错,所以写了一个这样的小脚本帮助自己。
#!/usr/bin/perl -w
use strict;
use Getopt::Long;
use constant USAGE =>
"Usage:".
"\t$0 -f file\n".
"Options:\n".
"\t-f file contains ip and netmask, each line like '192.168.1.0\\24'\n".
"\t-v display the version\n".
"\t-h Help!\n";
use constant VERSION => "Version: 1.0.0\n";
my $file;
my @line;
my @record;
my $hostpart=0;
my @ip;
my $netpart;
my $start;
my $end;
my $help;
my $version;
GetOptions(
"file=s" => \$file,
"help!" => \$help,
"version!" => \$version,
) or die USAGE;
die USAGE if ($help);
die USAGE if (!$file);
if ($version){
print VERSION;
exit (0);
}
open (IN,"< $file" || die "$!");
while(){
chomp;
s/\s+//g;
push @line,$_;
}
close(IN);
foreach my $tmp (@line) {
@record = split(/\//,$tmp);
@ip = split(/\./,$record[0]);
if ($record[1] >= 24){
$start=$record[0];
$netpart="$ip[0]"."."."$ip[1]"."."."$ip[2]".".";
$hostpart+=2**(32-$record[1]);
$end=$ip[3]+($hostpart)-1;
$end="$netpart"."$end";
print "$start~$end\n";
$hostpart=0;
}
elsif($record[1] >= 16 && $record[1] <= 23 ){
$start=$record[0];
$netpart="$ip[0]"."."."$ip[1]".".";
$hostpart+=2**(32-8-$record[1]);
$end=$ip[2]+($hostpart)-1;
$end="$netpart"."$end"."."."255";
print "$start~$end\n";
$hostpart=0;
}
elsif($record[1] >= 8 && $record[1] <= 16){
$start=$record[0];
$netpart="$ip[0]".".";
$hostpart+=2**(32-8-8-$record[1]);
$end=$ip[1]+($hostpart)-1;
$end="$netpart"."$end"."."."255"."."."255";
print "$start~$end\n";
$hostpart=0;
}
else{
$start=$record[0];
$netpart="$ip[0]".".";
$hostpart+=2**(32-8-8-8-$record[1]);
$end=$ip[0]+$hostpart-1;
$end="$end"."."."255"."."."255"."."."255";
print "$start~$end\n";
$hostpart=0;
}
}
阅读(1811) | 评论(0) | 转发(0) |