Skip to content

Instantly share code, notes, and snippets.

@2no
Created July 30, 2011 09:48
Show Gist options
  • Save 2no/1115370 to your computer and use it in GitHub Desktop.
Save 2no/1115370 to your computer and use it in GitHub Desktop.
IP とサブネットマスクから範囲を計算(IPv4 のみ)
var PATTERN = /^(\d|[01]?\d\d|2[0-4]\d|25[0-5])\.(\d|[01]?\d\d|2[0-4]\d|25[0-5])\.(\d|[01]?\d\d|2[0-4]\d|25[0-5])\.(\d|[01]?\d\d|2[0-4]\d|25[0-5])\/(\d|[012]?\d|3[0-2])?$/;
var BIT_STR = "11111111111111111111111111111111";
var MIN_BIT = 8;
var MAX_BIT = 30;
function calcIp(ip)
{
var result = [];
var ip = ip.match(PATTERN);
if (ip) {
ip[5] = ip[5] < MIN_BIT ? MIN_BIT
: MAX_BIT < ip[5] ? MAX_BIT : ip[5];
var total = ip[1] << 24 | ip[2] << 16 | ip[3] << 8 | ip[4];
var bit = BIT_STR.length - ip[5];
var mask = [
parseInt(BIT_STR.substring(bit ), 2) << bit,
parseInt(BIT_STR.substring(ip[5]), 2)
];
var rst = [
total & mask[0],
total | mask[1]
];
var min = [
255 & rst[0] >> 24,
255 & rst[0] >> 16,
255 & rst[0] >> 8,
255 & rst[0],
];
var max = [
255 & rst[1] >> 24,
255 & rst[1] >> 16,
255 & rst[1] >> 8,
255 & rst[1],
];
result = [ min, max,
[ min[0], min[1], min[2], min[3] + 1 ],
[ max[0], max[1], max[2], max[3] - 1 ]
];
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment