Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 706
James Mnatzaganian Avatar asked Feb 19 '23 05:02

James Mnatzaganian


1 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
like image 115
Borodin Avatar answered Mar 05 '23 04:03

Borodin