Ruby version of Perl Net::CIDR::Lite?

I’m updating an old Perl script to Ruby and having a problem with finding a replacement for one Perl library.

In the Perl script we use Net::CIDR::Lite, which takes a start and end ip address range and outputs a CIDR string.

This is a Perl example that shows the functionality:

#!/usr/bin/perl

use Net::CIDR::Lite;
$cidrblocks = Net::CIDR::Lite->new;
$cidrblocks->add_range("109.152.0.0-109.152.7.255");

$coveragezone = "";

@cidrlist = $cidrblocks->list();

$cidrcount=0;
    while ( defined $cidrlist[$cidrcount] ) {
            $coveragezone .= "$cidrlist[$cidrcount]";
    }
    continue {
            $cidrcount++;
    }

print "$coveragezone";

This script returns a string:

=> 109.152.0.0/21

Does anyone know of a Ruby lib or gem I could use to duplicate the functionality of the add_range call?

$cidrblocks = Net::CIDR::Lite->new;
$cidrblocks->add_range("109.152.0.0-109.152.7.255");

Answers


You can either use the built-in IPAddr class which also handles CIDR networks, or you use the ipaddress gem which provides some additional helpers.

A simple example would be:

cidrblocks = []
cidrblocks << IPAddr.new("109.152.0.0/21")

included = cidrblocks.find{|net| net.include?("109.152.6.123") }

I prefer the NetAddr gem, in particular its NetAddr::CIDR class.

It's a very rich IPv4/IPv6 gem.


Looking through the three modules I know of, Ruby's built-in IPAddr, NetAddr and IPAddress, mentioned by @holgerjust, none of them give us the ability to supply a start IP and end IP and return the resulting network. They all assume a CIDR form of the network, and then work toward testing the individual IPs to see if they fit into the subnet, or using that subnet definition to generate the IPs themselves.


I found a ruby module which does this translation see

http://wejn.org/stuff/cidr.rb.html

have included it in my rails app and it's perfect


Can't find a suitable gem? Do what comes naturally - reimpliment the Perl module in Ruby.


While this may not be entirely relevant to your question, I ported part of CIDR::Lite to Ruby:

https://github.com/noahhaon/cidr-lite-ruby

I found its performance to be far better than the available ruby alternatives at the time for merging very large sets of overlapping CIDRs.

HTH


Need Your Help

What is Delphi Prism LineFeed

delphi delphi-prism oxygene

What is the equivalent of C#'s \n and Visual Basic's vbCRLF or vbNewLine in Delphi Prism? Do I have to use Environment.NewLine?

Plotting a ROC curve in scikit yields only 3 points

python validation machine-learning scikit-learn roc

TLDR: scikit's roc_curve function is only returning 3 points for a certain dataset.