Jeff Pang wrote:
> Hello,
Hello,
> I have a text file which contains lots of IPs,like:
>
> 58.253.0.0/16;
> 58.254.0.0/16;
> 58.255.0.0/16;
> 60.0.0.0/16;
> 60.1.0.0/16;
> 60.10.0.0/16;
> 60.16.0.0/16;
> 60.17.0.0/16;
> 60.18.0.0/16;
> 60.19.0.0/16;
> 60.2.0.0/16;
> 60.20.0.0/16;
> 60.21.0.0/16;
> 60.22.0.0/16;
> 60.23.0.0/16;
> 60.3.0.0/16;
>
> My question is,given an IP,ie 59.32.232.33,how can I know it exists in
> this file or not?
> Is there a module already?thanks.
This may help:
$ perl -le'
use warnings;
use strict;
use Socket;
my $file = <<FILE;
58.253.0.0/16;
58.254.0.0/16;
58.255.0.0/16;
60.0.0.0/16;
60.1.0.0/16;
60.10.0.0/16;
60.16.0.0/16;
60.17.0.0/16;
60.18.0.0/16;
60.19.0.0/16;
60.2.0.0/16;
60.20.0.0/16;
60.21.0.0/16;
60.22.0.0/16;
60.23.0.0/16;
60.3.0.0/16;
FILE
open my $fh, "<", \$file or die "Cannot open $file: $!";
my @ips;
while ( <$fh> ) {
next unless /^(\d+\.\d+\.\d+\.\d+)\/(\d+)/;
my $mask = "\0\0\0\0";
vec( $mask, $_, 1 ) = 1 for 0 .. ( 31 - $2 );
push @ips, { ip => inet_aton( $1 ), mask => $mask };
}
for my $ip ( qw/ 59.32.232.33 60.19.232.33 / ) {
for my $cmp ( @ips ) {
if ( ( inet_aton( $ip ) & $cmp->{ mask } ) eq $cmp->{ ip } ) {
print "$ip exists in file."
}
}
}
'
60.19.232.33 exists in file.
John
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/