function ipToInt(ip) {
return ip.split('.').reduce((acc, octet, index) => {
return acc + (parseInt(octet, 10) << (24 - index * 8));
}, 0);
}
function maskToPrefix(mask) {
const maskInt = ipToInt(mask);
let prefix = 0;
for (let i = 31; i >= 0; i--) {
if ((maskInt & (1 << i)) !== 0) prefix++;
else break;
}
return prefix;
}
function intToIp(int) {
return [
(int >>> 24) & 0xff,
(int >>> 16) & 0xff,
(int >>> 8) & 0xff,
int & 0xff
].join('.');
}
function calculateIPRange(ip, mask) {
const ipInt = ipToInt(ip);
const maskInt = ipToInt(mask);
const prefix = maskToPrefix(mask);
const hostBits = 32 - prefix;
const networkInt = ipInt & maskInt;
let startInt, endInt;
if (hostBits === 0) {
startInt = networkInt;
endInt = networkInt;
} else {
startInt = networkInt + 1;
const broadcastInt = networkInt | ((1 << hostBits) - 1);
endInt = broadcastInt - 1;
}
return {
start: intToIp(startInt),
end: intToIp(endInt)
};
}
const example1 = calculateIPRange('10.56.101.1', '254.0.0.0');
console.log('示例1结果:', example1);
const example2 = calculateIPRange('10.0.0.5', '255.255.255.252');
console.log('示例2结果:', example2);
const example3 = calculateIPRange('172.16.0.1', '255.255.255.255');
console.log('示例3结果:', example3);