IP
by Ansmtz
JavaScript
/* inRange("192.168.4.27", "192.168.0.0/16") */
const inRange = (ip, range) => {
const ipArray = ip.split('.');
const [address, prefixLength] = range.split('/');
const addressArr = address.split('.');
const sections = +prefixLength / 8;
let bytes = 32 - prefixLength;
let lastIndex = 0;
/* mask checking */
for(let i = 0; i < sections; i++){
if(ipArray[i] !== addressArr[i]){
return false;
}
lastIndex = i;
}
for(let n = lastIndex; n < ipArray.length; n++){
const binary = ipArray[n].toString(2);
bytes -= binary.length;
if(bytes < 0){
return false;
}
}
return true;
}
console.log(inRange("192.168.4.27", "192.168.0.0/16"));
console.log(inRange("192.168.4.27", "192.168.1.0/24"));
console.log(inRange("198.51.100.0", "198.51.100.0/24"));
console.log(inRange("10.255.255.255", "10.0.0.0/8"));