Re: matching the network segment

From: Joe Smith (Joe.Smith_at_inwap.com)
Date: 07/30/04


Date: Fri, 30 Jul 2004 12:21:33 GMT

Facco Eloelo wrote:

> open FH,'<','d:\a\IPSegment.txt';
> while (<FH>) {
> chomp($_);
> $ip{$_}=0;
> }

You are not doing anything with the number after the '/', and you should.

> 219.111.192.0/18

That one specification translates into 16384 individual IP addresses.

   $ip{'219.111.192.0'} = 0;
   $ip{'219.111.192.1'} = 0;
   $ip{'219.111.192.2'} = 0;
   $ip{'219.111.192.3'} = 0;
        ...
   $ip{'219.111.223.252'} = 0;
   $ip{'219.111.223.253'} = 0;
   $ip{'219.111.223.254'} = 0;
   $ip{'219.111.223.255'} = 0;

> if ($ip{'$domip'} > 0) {
> print FH2 $rec,"\n";
> $ip{'$domip'}++; #increment a counter here, output from hash
> }

I would use one line for that: [No single quotes around hash keys!]
        print FH2 $rec,"\n" if $ip{$domip}++; # Print duplicates after first

####################################################################

As for your segments, this may be helpful:

linux% cat temp.pl
use strict; use warnings;
use Socket;

my @data = qw( 219.111.192.0/18 68.132.0.0/17 67.146.0.0/16 192.162.0.0/16
                152.172.0.0/16 34.132.0.0/14 97.208.0.0/13 128.0.0.0/16 );

sub cidr {
   my($base,$bits) = split '/',$_[0]; # Assumes that $base really lowest
   my $ip4 = sprintf "%u",(unpack "N",inet_aton $base);
   ( $ip4, $ip4 + 2**(32-$bits)-1 ); # Return low and high
}

foreach my $segment (@data) {
   my($lo,$hi) = cidr($segment);
   printf "%17s = %10s .. %10s (%8x to %8x)\n", $segment, $lo, $hi, $lo, $hi;
}

linux% perl temp.pl
  219.111.192.0/18 = 3681533952 .. 3681550335 (db6fc000 to db6fffff)
     68.132.0.0/17 = 1149501440 .. 1149534207 (44840000 to 44847fff)
     67.146.0.0/16 = 1133641728 .. 1133707263 (43920000 to 4392ffff)
    192.162.0.0/16 = 3231842304 .. 3231907839 (c0a20000 to c0a2ffff)
    152.172.0.0/16 = 2561409024 .. 2561474559 (98ac0000 to 98acffff)
     34.132.0.0/14 = 579076096 .. 579338239 (22840000 to 2287ffff)
     97.208.0.0/13 = 1641021440 .. 1641545727 (61d00000 to 61d7ffff)
      128.0.0.0/16 = 2147483648 .. 2147549183 (80000000 to 8000ffff)