Home > Web Front-end > JS Tutorial > How to use javascript to determine whether two IP addresses are in the same network segment_javascript skills

How to use javascript to determine whether two IP addresses are in the same network segment_javascript skills

WBOY
Release: 2016-05-16 17:09:25
Original
2165 people have browsed it

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:

Copy code The code is as follows:

/ **
* [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;
}
}
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template