Skip to content

Instantly share code, notes, and snippets.

@wheresjames
Created May 3, 2017 19:12
Show Gist options
  • Save wheresjames/bc45b9e2d1216867e57a8f90626083cb to your computer and use it in GitHub Desktop.
Save wheresjames/bc45b9e2d1216867e57a8f90626083cb to your computer and use it in GitHub Desktop.
Generate range of possible subnets for an IP Address

Generate range of possible subnets for an IP Address

function ip2num(ip)
{
var a = ip.split('.');
return (+a[0] << 24) | (+a[1] << 16) | (+a[2] << 8) | +a[3];
}
function num2ip(n)
{
return [((n >> 24) & 0xff), ((n >> 16) & 0xff), ((n >> 8) & 0xff), (n & 0xff)].join('.');
}
function genSubnets(ip, min, max)
{
var ipn = ip2num(ip);
min = min ? min : 8;
max = max ? max : 32;
var m = 0;
for (var i = 0; i < min; i++)
m = (m >> 1) | 0x80000000;
var a = [];
for (var i = min; i <= max; i++)
{
a[a.length] = num2ip(ipn & m) + '/' + i;
m = (m >> 1) | 0x80000000;
}
return a;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment