Home  >  Article  >  Web Front-end  >  Javascript example code to determine whether two IPs are in the same network segment

Javascript example code to determine whether two IPs are in the same network segment

高洛峰
高洛峰Original
2016-12-05 09:38:571418browse

avascript determines whether two IPs are in the same network segment

The following script does not determine the IP format, but only determines whether the two IPs are in the same network segment.

Example, Javascript determines whether two IPs are on the same network segment.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
  
 <HEAD>
  <TITLE>
   IP段信息检测_www.manongjc.com
  </TITLE>
  <script language="JavaScript" type="text/javascript">
   function checkSameNetMask(value1, value2, netmask) {
    var ip1 = new Array();
    var ip2 = new Array();
    var nm = new Array();
    ip1 = value1.split(".");
    ip2 = value2.split(".");
    nm = netmask.split(".");
    var ip1_2s = "";
    var ip2_2s = "";
    var inm2s = "";
    var index = 0;
    for (index = 0; index < 4; index++) {
     var ip_1 = new Array();
     var ip_2 = new Array();
     var n_m = new Array();
     ip_1 = parseInt(ip1[index]).toString(2);
     ip_2 = parseInt(ip2[index]).toString(2);
     n_m = parseInt(nm[index]).toString(2);
     var tindex;
     for (tindex = 0; tindex < (8 - ip_1.length); tindex++) {
      ip1_2s += "0";
     }
     ip1_2s += ip_1;
     for (tindex = 0; tindex < (8 - ip_2.length); tindex++) {
      ip2_2s += "0";
     }
     ip2_2s += ip_2;
     for (tindex = 0; tindex < (8 - n_m.length); tindex++) {
      inm2s += "0";
     }
     inm2s += n_m;
    }
    var len = inm2s.length;
    var ip_12 = new Array();
    var ip_22 = new Array();
    var n_m_2 = new Array();
    ip_12 = ip1_2s.split("");
    ip_22 = ip2_2s.split("");
    n_m_2 = inm2s.split("");
    for (index = 0; index < len; index++) {
     if (n_m_2[index] == "1") {
      if (ip_12[index] != ip_22[index]) {
       alert("不在同一网段");
       return false;;
      }
     }
    }
    alert("在同一网段");
    return true;
   }
  </script>
 </HEAD>
  
 <BODY>
  <input name="Ip1" id="Ip1" maxlength=15>
  <br>
  <input name="Ip2" id="Ip2" maxlength=15>
  <br>
  <input name="netmask" id="netmask" maxlength=15>
  <input type="button" value="计算" onClick="checkSameNetMask( document.getElementById(&#39;Ip1&#39;).value , document.getElementById(&#39;Ip2&#39;).value , document.getElementById(&#39;netmask&#39;).value ); ">
 </BODY>
 
</HTML>


Statement:
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