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";
}
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.