0

我有两个子网值,例如:

答:123.23.34.45/23 B:102.34.45.32/32

我想检查值 B 是否在 A 的范围内。我尝试使用库网络掩码,任何人都可以建议任何其他库或任何解决方案来实现这一点。

4

1 回答 1

1

这是一个快速的片段:

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>

于 2021-02-18T15:15:13.997 回答