我正在尝试将最大可用主机地址的数值转换为 CIDR 表示法 IP,例如:192.168.1.1/28 的可用主机空间为 14。但是 192.168.1.1/30 和 /31 都有可用的主机2的空间,这是问题发挥作用的地方。下面的代码显示了预期值和实际值:
let ip = "192.168.1.1";
console.log("max hosts of 14, expected: 255.255.255.240, got: " + test(ip, 14));
//the problem, these should give the correct result respectively
console.log("max hosts of 2, expected: 255.255.255.254, got: " + test(ip, 2));
console.log("max hosts of 2, expected: 255.255.255.252, got: " + test(ip, 2));
let test = function(ip, maxHosts){
let numericNetmask = (maxHosts ^ 0xFFFFFFFF) - 1;
let str = [];
for (let shift = 24; shift > 0; shift -= 8) {
str.push(((numericNetmask >>> shift) & 0xFF).toString());
}
str.push((numericNetmask & 0xFF).toString());
return str.join(".");
};
现在我当然明白,在这种情况下,将最大主机数转换回网络掩码是不可能的,但是,考虑到 IP 地址,这可能吗?(注意:这是类超网)。
当然,在正常的用例中,例如通过将 CIDR 网络掩码存储为值可以“破解”该表单,但我希望有一个替代方案。