Usage: hasSameIPv6Subnet("2001:db8:1::1111/64", "2001:db8:1::ffff")
Function is below,
var hasSameIPv6Subnet = function (ipAndMask, compareIp) {
var convertToIPv6BinaryFormat = function (ip) {
var colonCount = ip.match(/:/g).length;
if (colonCount > 7) {
return false
}
var zeroPartsCount = 8 - colonCount;
var fillZeroStr = '';
// Filled '::' to ':0000:0000:0000:0000:'
// ex: convert '2001:db8:1::ff01' to '2001:db8:1:0000:0000:0000:0000:ff01'
for (i=0;i<zeroPartsCount;i++) {
fillZeroStr = fillZeroStr + '0000:';
}
var ipTwoParts = ip.split('::');
ip = ipTwoParts[0] + ':' + fillZeroStr + ipTwoParts[1];
var ipParts = ip.split(':');
var newIp = '';
// Filled '' with '0'
for (i=0;i<ipParts.length;i++) {
ipParts[i] = ipParts[i].padStart(4, '0');
newIp = newIp + ipParts[i];
}
var fillIPv6Parts = ['', '', '', '', '', '', '', ''];
var j = 0;
for (i=0;i<32;i+=4) {
fillIPv6Parts[j] = newIp.substr(i, 4);
j++;
}
// Covert IPv6 to Binary.
var temp = 0;
var binaryIp = '';
for (i=0;i<fillIPv6Parts.length;i++) {
temp = parseInt(fillIPv6Parts[i], 16);
binaryIp = binaryIp + temp.toString(2).padStart(16, '0');
}
binaryIp = binaryIp.padStart(128, '0');
return binaryIp;
};
if (ipAndMask === '') {
return false;
}
var ipAndMaskParts = ipAndMask.split('/');
var ip = ipAndMaskParts[0];
var mask = ipAndMaskParts[1];
var binaryIp = convertToIPv6BinaryFormat(ip);
var binaryCompareIp = convertToIPv6BinaryFormat(compareIp);
if (binaryIp === false || binaryCompareIp === false) {
return false;
}
if (binaryIp.substr(0, mask) !== binaryCompareIp.substr(0, mask)) {
return false;
}
return true;
};
|
留言列表