ip范围

看到一个判断ip的帖子,应该会有用吧。

有如下两个文本文件(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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值