To determine whether two IP addresses are in the same CIDR Block, perform and calculate their IP addresses and subnet masks respectively, and the result is the network number. The specific implementation is as follows, for more information, see 1) Basic Ideas:
To determine whether two IP addresses are in the same CIDR Block, perform and calculate the IP addresses and subnet masks respectively. The result is the network number. If the network number is the same, the IP addresses are in the same subnet, otherwise, it is not in the same subnet.
2) specific implementation:
The Code is as follows:
/**
* [IsEqualIPAddress: determines whether two IP addresses are in the same CIDR block]
* @ Param {[String]} addr1 [address 1]
* @ Param {[String]} addr2 [address 2]
* @ Param {[String]} mask [subnet mask]
* @ Return {Boolean} [true or false]
*/
Function isEqualIPAddress (addr1, addr2, mask ){
If (! Addr1 |! Addr2 |! Mask ){
Console. log ("parameters cannot be blank ");
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 ("in the same network segment ");
Return true;
} Else {
Console. log ("not in the same network segment ");
Return false;
}
}