Perl: Obtain range of IP addresses not in the given list

I'm trying to create ranges of IP addresses based off a file containing a series of IP addresses. The ranges I'm trying to create are those that are not in the file. For example, If I had the following IP addresses:

129.32.0.1
27.45.2.2
129.32.0.2
65.18.2.4

The output should be 0.0.0.0-27.45.2.1,27.45.2.3-65.18.2.3,65.18.2.5-129.32.0.0,129.32.0.3-255.255.255.255

What I've currently done is extract the IPs from an input file and store them into a sorted array (ascending).

#!/usr/bin/perl -w
use strict;                                           
use Sort::Key::IPv4 qw(ipv4sort);                                                          
my $list = 'C:\Desktop\IPs.txt';
my $ipRange;
my @ips;
my $i = 0;

# Get IP Addresses into array
open(FILE, $list);

while (<FILE>) {
    chomp($_);
    $ips[$i] = ($_);
    ++$i;
}

# Sort IP Addresses
my @sorted = ipv4sort @ips;

# Create IP Ranges

I'm hoping that there is something on CPAN that can help me out. I've seen modules that can determine if an IP address is in a range, but have yet to see anything that can split a range.

Answers


I suggest the comprehensive Net::CIDR::Set module

This code seems to provide what you need

use strict;
use warnings;

use Net::CIDR::Set;

open my $fh, '<', 'C:\Desktop\IPs.txt' or die $!;

my $range = Net::CIDR::Set->new;
while (<$fh>) {
  chomp;
  $range->add($_);
}
$range->invert;
print $range->as_string(2);

output

0.0.0.0-27.45.2.1, 27.45.2.3-65.18.2.3, 65.18.2.5-129.32.0.0, 129.32.0.3-255.255.255.255

Need Your Help

Building CoffeesSript browser applications - namespace and scope issues

javascript coffeescript

I am new to CoffeeScript and am trying to get a feel for the best way of managing and building a complex application that will run in the browser. So, I am trying to determine what is the best way...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.