自定义的子网范围如下:

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:
 
 
  
  1. #!/usr/bin/perl 
  2. use strict; 
  3. use warnings; 
  4. use Data::Dumper; 
  5. my %hash; 
  6. while(<DATA>){ 
  7.     chomp; 
  8.     my($ip,$netmask)=split/\//; 
  9.     my $ipbit = unpack("B32",pack("C4", (split/\./,$ip))); 
  10.     my $net = substr("$ipbit",0,"$netmask"); 
  11.     push @{$hash{$net}}, $ip,$netmask; 
  12. #print Dumper \%hash; 
  13. my @testip=qw{192.168.1.5 219.111.193.1 219.111.1.2}; 
  14. foreach my $kipbit (keys %hash){ 
  15.     my $netmask = $hash{$kipbit}[1]; 
  16.     my $netip = $hash{$kipbit}[0]; 
  17.       foreach my $testkip (@testip){ 
  18.             my $testipbit = unpack("B32",pack("C4", (split/\./,$testkip))); #C4转化为char类型的数据类型,C4也可以写作CCCC,B32将IP地址转化为32位的bit。 
  19.              $testipbit = substr("$testipbit",0,"$netmask"); 
  20.             if($kipbit == $testipbit){ 
  21.                 print "$netip/$netmask\n"
  22.             } 
  23.       } 
  24. __DATA__ 
  25. 192.168.0.0/16 
  26. 219.111.192.0/18 
  27. 68.132.0.0/17 
  28. 61.135.0.0/16 
  29. 192.162.0.0/16 
  30. 152.172.0.0/16 
  31. 34.132.0.0/14 
  32. 97.208.0.0/13