[removed] Is IP In One Of These Subnets?

前端 未结 6 551
独厮守ぢ
独厮守ぢ 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:21

    Convert the lower ip and the upper ip in the range to integers and store the range in the db then make sure both columns are indexed.

    Off the top of my head (pseudo code):

    function ipmap(w,x,y,z) {
      return 16777216*w + 65536*x + 256*y + z;
    }
    
    var masks = array[ipmap(128,0,0,0), ipmap(196,0,0,0), ..., ipmap(255,255,255,255)]
    
    function lowrange(w, x, y, z, rangelength) {
      return ipmap(w, x, y, z) & masks[rangelength]
    }
    
    function hirange(w, x, y, z, rangelength) {
      return lowrange(w, x, y, z, ,rangelength) + ipmap(255,255,255,255) - masks[rangelength];
    }
    

    That ought to do it.

    To find whether a particular ip falls in any of the ranges, convert it to an integer and do:

    SELECT COUNT(*) FROM ipranges WHERE lowrange <= 1234567 AND 1234567 <= highrange
    

    The query optimizer should be able to speed this up greatly.

提交回复
热议问题