Home > Web Front-end > JS Tutorial > body text

Javascript 判断两个IP是否在同一网段

WBOY
Release: 2016-06-01 09:54:38
Original
1832 people have browsed it

以下脚本不做IP格式的判断,只判断两个IP是否在同一网段。

例子,Javascript判断两个IP是否在同一网段。

<code class="language-html">

  
  
    <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>
  
  
  
    <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('Ip1').value , document.getElementById('Ip2').value , document.getElementById('netmask').value ); ">
  

</code>
Copy after login

需要的码农可以拿去参考。

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!