Chinaunix首页 | 论坛 | 博客
  • 博客访问: 79939
  • 博文数量: 32
  • 博客积分: 1526
  • 博客等级: 上尉
  • 技术积分: 270
  • 用 户 组: 普通用户
  • 注册时间: 2009-10-28 13:56
文章分类

全部博文(32)

文章存档

2012年(1)

2011年(15)

2010年(1)

2009年(15)

我的朋友
最近访客

分类: Python/Ruby

2011-12-04 13:12:01

在工作中通常需要将类似“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;
}
}
阅读(1760) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~