need an algorithm for collapsing netblock ranges into lists of superset ranges

后端 未结 4 896
名媛妹妹
名媛妹妹 2020-12-01 16:28

My math-fu is failing me! I need an efficient way of reducing network ranges to supersets, e.g. if I input list of IP ranges:

  • 1.1.1.1 to 2.2.2.5
  • 1.1.1
4条回答
  •  广开言路
    2020-12-01 17:11

    You know that you can easily convert IPv4 addresses to int numbers (int32 numbers), do you? Working with int numbers is much easier. So basically every address is a number in the range 0 to 2^32. Every range has a start number and an end number. Your example

    1.1.1.1 to 2.2.2.5
    1.1.1.2 to 2.2.2.4
    

    can be written as

    16,843,009 to 33,686,021
    16,843,010 to 33,686,020
    

    So it's pretty easy to see if one range is within the other range. A range is completely within the other range if the following condition is given

    startIP2 >= startIP1 && startIP2 <= endIP1 &&
    endIP1 >= startIP1 && endIP2 <= endIP1
    

    In that case the range startIP2-endIP2 is completely within startIP1-endIP1. If only the first line is true, then startIP2 is within the range startIP1-endIP1, but the end is beyond the range. If only the second line is true, the endIP is within the range, but the start IP is beyond the range. In that case, if only one line is true, you need to expand the range at the beginning or at the end. If both lines are false, the ranges are completely disjoint, in that case they are two completely independent ranges.

提交回复
热议问题