判断ip是否属于某个网段

function isInRange(ip, segment) {
      ipBlocks = ip.split(".");
      binaryIp = (Number(ipBlocks[0]) << 24) | (Number(ipBlocks[1]) << 16) | (Number(ipBlocks[2]) << 8) | (Number(ipBlocks[3]))
      type = Number(segment.split("/")[1])
      mask = 0xFFFFFFFF << (32 - type)
      segmentIpBlocks = segment.split("/")[0].split(".")
      binarySegmentIp = (Number(segmentIpBlocks[0]) << 24) | (Number(segmentIpBlocks[1]) << 16) | (Number(segmentIpBlocks[2]) << 8) | (Number(segmentIpBlocks[3]))
      return (binaryIp & mask) == (binarySegmentIp & mask);
}
console.log(999, isInRange('192.168.158.49', '192.168.158.1/24'));

 

posted @ 2021-10-12 11:10  帝沐  阅读(393)  评论(0编辑  收藏  举报