Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve max / min IPs from CIDR range

I would like to get the maximum and minimum IPs from a CIDR block - My current code works fine except for some IPs that return negative numbers on the minimum number. Below is my existing code and output.

function long2ip (proper_address) {
// Converts an (IPv4) Internet network address into a string in Internet standard dotted format
//
// version: 1109.2015
// discuss at: http://phpjs.org/functions/long2ip
// +   original by: Waldo Malqui Silva
// *     example 1: long2ip( 3221234342 );
// *     returns 1: '192.0.34.166'
var output = false;
if (!isNaN(proper_address) && (proper_address >= 0 || proper_address <= 4294967295)) {
    output = Math.floor(proper_address / Math.pow(256, 3)) + '.' +
    Math.floor((proper_address % Math.pow(256, 3)) / Math.pow(256, 2)) + '.' +
    Math.floor(((proper_address % Math.pow(256, 3)) % Math.pow(256, 2)) / Math.pow(256, 1)) + '.' +
    Math.floor((((proper_address % Math.pow(256, 3)) % Math.pow(256, 2)) % Math.pow(256, 1)) / Math.pow(256, 0));
}
return output;
}

function cidrToRange(cidr) {
var range = [2];
cidr = cidr.split('/');
var longIp = ip2long(cidr[0]);
var mask = ((-1 << (32 - cidr[1])));
var longIp = ip2long(cidr[0]);
range[0] = long2ip(longIp & ((-1 << (32 - cidr[1]))));
range[1] = long2ip(longIp + Math.pow(2, (32 - cidr[1])) - 1);
return range;
}



console.log(cidrToRange('157.60.0.0/16')); // returns [ '-99.-196.0.0', '157.60.255.255' ]
console.log(cidrToRange('157.56.0.0/14')); // returns [ '-99.-200.0.0', '157.59.255.255' ]
console.log(cidrToRange('127.0.0.1/8')); // returns [ '127.0.0.0', '128.0.0.0' ]

I am testing in node.js but cannot seem to get the above ranges to work as I would like. Any help is appreciated.

Mark

like image 955
Mark Willis Avatar asked Dec 03 '12 12:12

Mark Willis


1 Answers

Just for the reference this is correct cidrToRange code in javascript:

function cidrToRange(cidr) {
   var range = [2];
   cidr = cidr.split('/');
   var cidr_1 = parseInt(cidr[1])
   range[0] = long2ip((ip2long(cidr[0])) & ((-1 << (32 - cidr_1))));
   start = ip2long(range[0])
   range[1] = long2ip( start + Math.pow(2, (32 - cidr_1)) - 1);
   return range;
}

For example

cidrToRange('192.168.62.156/27') gives ["192.168.62.128", "192.168.62.159"] and that is exactly what we need.

like image 183
drKreso Avatar answered Sep 30 '22 15:09

drKreso