1) Basic idea:
To determine whether two IP addresses are in the same network segment, perform an AND operation on their IP addresses and subnet masks respectively. The result obtained is the network number. If the network number is the same, it is The same subnet, otherwise, not the same subnet.
2) Specific implementation:
/ **
* [isEqualIPAddress determines whether two IP addresses are in the same network segment]
* @param {[String]} addr1 [Address one]
* @param {[String]} addr2 [Address two]
* @param {[String]} mask [Subnet mask]
* @return {Boolean} [true or false]
*/
function isEqualIPAddress (addr1,addr2,mask){
if(!addr1 || !addr2 || !mask){
console.log("Each parameter cannot be empty ");
return false;
}
var
res1 = [],
res2 = [];
addr1 = addr1.split(".");
addr2 = addr2.split(".");
mask = mask.split(".");
for(var i = 0,ilen = addr1.length; i < ilen ; i = 1) {
res1.push(parseInt(addr1[i]) & parseInt(mask[i]));
res2.push(parseInt(addr2[i]) & parseInt(mask[i]));
}
if(res1.join(".") == res2.join(".")){
console.log("On the same network segment");
return true;
}else{
console.log("Not in the same network segment");
return false;
}
}