有如下两个文本文件(IPlist.txt和IPsegment.txt),IPlist.txt包含有一些网站的IP地址,如何编程判断这些IP地址是否属于IPsegment.txt所列的网段中。
匹配的结果输出到文本文件matchinglist.txt中。
三个文件的格式如下:
IPlist.txt
www.yahoo.com,66.94.230.51
www.baidu.com,202.108.250.249
www.sina.com.cn,61.135.152.77
www.sohu.com,61.135.150.75
IPsegment.txt
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
matchinglist.txt
www.sina.com.cn,61.135.152.77
#!/usr/bin/perl
open(FF,"IPlist.txt");
my %name;
my %net;
while(<FF>){
s/[\015\012]//;
my ($t1,$t2) = split(/,/);
$name{$t1} = $t2;
}
close(FF);
open(FF,"IPsegment.txt");
while(<FF>){
s/[\015\012]//;
my ($t1,$t2) = split(/\//);
$net{$t1} = $t2;
}
close(FF);
for $net (keys %net){
my $netmask = $net{$net};
my $net_bits1 = &bitsIP($net,$netmask);
for $name (keys %name){
my $net_bits2 = &bitsIP($name{$name},$netmask);
if($net_bits2 eq $net_bits1){
print "$name,".$name{$name}."\n";
next;
}
}
}
#--取得bits of net address
sub bitsIP(){
my($ip,$netmask)= @_;
my @ip =split(/,/,$ip);
my $b = unpack("B32", pack("C4",$ip[0],$ip[1],$ip[2],$ip[3]));
my $substr= substr($b,0,$netmask);
return $substr;
}