How to determine whether two IP addresses are in the same CIDR block using javascript _ javascript tips-js tutorial

Source: Internet
Author: User
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;
}
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.