perl计算IP所在的子网范围
自定义的子网范围如下:192.168.0.0/16
219.111.192.0/18
68.132.0.0/17
61.135.0.0/16
192.162.0.0/16
152.172.0.0/16
34.132.0.0/14
97.208.0.0/13
有以下几个IP:192.168.1.5 219.111.193.1 219.111.1.2,要求计算是否在以上自网之中,如果在,则输出此IP所在的自网
code:
[*]#!/usr/bin/perl
[*]use strict;
[*]use warnings;
[*]use Data::Dumper;
[*]my %hash;
[*]while(){
[*] chomp;
[*] my($ip,$netmask)=split/\//;
[*] my $ipbit = unpack("B32",pack("C4", (split/\./,$ip)));
[*] my $net = substr("$ipbit",0,"$netmask");
[*] push @{$hash{$net}}, $ip,$netmask;
[*]}
[*]#print Dumper \%hash;
[*]my @testip=qw{192.168.1.5 219.111.193.1 219.111.1.2};
[*]foreach my $kipbit (keys %hash){
[*] my $netmask = $hash{$kipbit};
[*] my $netip = $hash{$kipbit};
[*] foreach my $testkip (@testip){
[*] my $testipbit = unpack("B32",pack("C4", (split/\./,$testkip))); #C4转化为char类型的数据类型,C4也可以写作CCCC,B32将IP地址转化为32位的bit。
[*] $testipbit = substr("$testipbit",0,"$netmask");
[*] if($kipbit == $testipbit){
[*] print "$netip/$netmask\n";
[*] }
[*] }
[*]}
[*]__DATA__
[*]192.168.0.0/16
[*]219.111.192.0/18
[*]68.132.0.0/17
[*]61.135.0.0/16
[*]192.162.0.0/16
[*]152.172.0.0/16
[*]34.132.0.0/14
[*]97.208.0.0/13
页:
[1]