[removed] Is IP In One Of These Subnets?

前端 未结 6 504
独厮守ぢ
独厮守ぢ 2021-01-30 23:26

So I have ~12600 subnets:

eg. 123.123.208.0/20

and an IP.

I can use a SQLite Database or an array or whatever

There was a similar question asked

6条回答
  •  余生分开走
    2021-01-31 00:12

    The best approach is IMO making use of bitwise operators. For example, 123.123.48.0/22 represents (123<<24)+(123<<16)+(48<<8)+0 (=2071670784; this might be a negative number) as a 32 bit numeric IP address, and -1<<(32-22) = -1024 as a mask. With this, and likewise, your test IP address converted to a number, you can do:

    (inputIP & testMask) == testIP
    

    For example, 123.123.49.123 is in that range, as 2071671163 & -1024 is 2071670784

    So, here are some tool functions:

    function IPnumber(IPaddress) {
        var ip = IPaddress.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/);
        if(ip) {
            return (+ip[1]<<24) + (+ip[2]<<16) + (+ip[3]<<8) + (+ip[4]);
        }
        // else ... ?
        return null;
    }
    
    function IPmask(maskSize) {
        return -1<<(32-maskSize)
    }
    

    test:

    (IPnumber('123.123.49.123') & IPmask('22')) == IPnumber('123.123.48.0')
    

    yields true.

    In case your mask is in the format '255.255.252.0', then you can use the IPnumber function for the mask, too.

提交回复
热议问题