简体   繁体   中英

Java code/library to merge continous CIDR blocks

is there any java api or library which can be used to merge multiple continuous cidr blocks.

For eg:

209.152.214.112/30
209.152.214.116/31
209.152.214.118/31

can be merged into 209.152.214.112/29 . But below cidr can not be merged since they are not continuous.

209.152.214.112/30
209.152.214.116/32
209.152.214.118/31

There is a library available in Java for this. The open-source IPAddress Java library has methods for merging addresses and subnets into prefix block subnets. Disclaimer: I am the project manager of the IPAddress library.

The following method "merge" shows the code, relying on the method mergeToPrefixBlocks from the library:

static IPAddress[] merge(String strs[]) {
    List<String> strList = Arrays.asList(strs);
    // convert first
    IPAddress first = new IPAddressString(strList.get(0)).getAddress(); 
    // convert remaining
    IPAddress others[] = strList.subList(1, strList.size()).stream().map(str -> new IPAddressString(str).getAddress()).toArray(IPAddress[]::new);  

    // merge first with remaining
    return first.mergeToPrefixBlocks(others);
}

The method can be demonstrated with your examples:

    System.out.println("blocks are " + Arrays.asList(merge(new String[] {"209.152.214.112/30", "209.152.214.116/31", "209.152.214.118/31"})));
    System.out.println("blocks are " + Arrays.asList(merge(new String[] {"209.152.214.112/30", "209.152.214.116/32", "209.152.214.118/31"})));

The output is:

blocks are [209.152.214.112/29]
blocks are [209.152.214.116/32, 209.152.214.118/31, 209.152.214.112/30]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM