in reply to Match only certain IP Addresses

You're falling into a very common mistake made in dealing with IP addresses. They're actually just a 32 bit number that happen to be commonly written in a really wierd way - dotted quad notation. Use the functions inet_ntoa and inet_aton (perldoc Socket for details) to get them into numbers, and you can quickly and easily sort them properly in perl. If you try to sort them with sort -u, then you'll have problems. For example, '10' will get placed before '5'. First, to get all of the IP addresses out of a text file, use a loop something like this (note that this assumes that there is at most one IP address per line)
my $ips; while(<INPUT>){ if (/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/{ push @ips, $1; } }
You don't really say what you IP range is, but I'll use for example the network 192.168.20.0 with a netmask of 255.255.255.0. This will weed out addresses only in this network, sort them numerically, and print them out.
use Socket; my $mask = 24; # 255.255.255.0 -> 24 bit netmask my $network = inet_aton("192.168.20.0"); my @myips; foreach $ip ( @iplist ) { $ip = inet_ntoa($ip); # convert ascii to decimal if( ($ip & $mask) == ($network & $mask) ){ push @myips, $ip; } } # this will sort the list properly since it's sorting the numbers. # otherwise it would sort 192.168.20.20 before 196.168.20.3 @myips = sort @myips; foreach $ip ( @myips ) { # print out the ascii format print inet_ntoa($ip), "\n"; }

Replies are listed 'Best First'.
Re: Re: Match only certain IP Addresses
by zengargoyle (Deacon) on Aug 06, 2003 at 22:02 UTC
    If you try to sort them with sort -u, then you'll have problems. For example, '10' will get placed before '5'.

    not necessarily true...

    $ cat sorttest 10.1.1.2 100.1.3.2 10.20.3.2 10.2.4.3 5.4.3.2 5.10.3.2 5.5.3.2 $ sort -t . -k 1,1n -k 2,2n -k 3,3n -k 4,4n sorttest 5.4.3.2 5.5.3.2 5.10.3.2 10.1.1.2 10.2.4.3 10.20.3.2 100.1.3.2
Re: Re: Match only certain IP Addresses
by bobn (Chaplain) on Aug 07, 2003 at 06:41 UTC

    I think you meant

    my $mask = inet_aton('255.255.255.0');
    and
    $ip = inet_aton($ip); # convert ascii to decimal

    --Bob Niederman, http://bob-n.com