javascriptsubnetnetmask

Want to check if a subnet is present in a given subnet or not using javascript


I have two subnet values eg:

A: 123.23.34.45/23 B: 102.34.45.32/32

I want to check if the value B falls in the range of A or not. I tried using the library netmask, can anyone suggest any other library or any solution for fulfilling this.


Solution

  • Here is a quick snippet:

    function ipNetwork(ip,network,mask)
    {
      ip = Number(ip.split('.').reduce(
    (ipInt, octet) => (ipInt << 8) + parseInt(octet || 0, 10), 0)
      );
      network = Number(network.split('.').reduce(
    (ipInt, octet) => (ipInt << 8) + parseInt(octet || 0, 10), 0)
      );
      mask = parseInt('1'.repeat(mask) + '0'.repeat(32 - mask), 2);
      return (ip & mask) == (network & mask);
    }
          
    function check()
    {
      alert(
        ipNetwork(
          document.test.ip_addr.value,
          document.test.network_addr.value,
          document.test.network_mask.value
        ) ? 'IP is inside the network' : 'IP is not from the network')
    }
    <form name="test">
      <label>
    Network address
    <input name="network_addr" value="123.23.34.45">
      </label>
    
      <label>
    Network mask
    <input name="network_mask" value="23">
      </label>
    
      <label>
    IP address
    <input name="ip_addr" value="102.34.45.32">
      </label>
    
      <button type="button" onclick="check()">Check</button>
    </form>