A good Java library for network math [closed]

2019-02-08 12:05发布

I'm looking for a Java library that is geared towards network math and already tested. Nothing particularly fancy, just something to hold ips and subnets, and do things like print a subnet mask or calculate whether an IP is within a given subnet.

Should I roll my own, or is there already a robust library for this?

3条回答
祖国的老花朵
2楼-- · 2019-02-08 12:43

The open-source IPAddress Java library can do ip address manipulation such as conversion to/from ipv4/ipv6 and subnet checking. Disclaimer: I am the project manager.

It handles various network math operations, such as masking, bitwise or, setting prefix lengths, switch address to prefix block, iterating through a subnet, checking containment, replacing address segments, reversing addresses, calculating subnet intersection, subtracting one subnet from another, and others.

Here is some example code for testing if an ipv6 address is in a given subnet:

    String ipv6 = "2001:db8:57AB:0000:0000:0000:0000:0001";
    String ipv6subnet = "2001:db8::/32";
    String ipv4 = "1.2.3.4";
    try {
        IPAddressString ipv6addrstr = new IPAddressString(ipv6);
        IPAddressString ipv6addrsubnetstr = new IPAddressString(ipv6subnet);
        IPAddressString ipv4addrstr = new IPAddressString(ipv4);

        IPAddress ipv6addr = ipv6addrstr.toAddress();
        IPAddress ipv6addrsubnet = ipv6addrsubnetstr.toAddress();
        IPAddress ipv4mappedaddr = ipv4addrstr.toAddress().toIPv6();

        System.out.println(ipv6addrsubnet + " contains " + ipv6addr + ": " + ipv6addrsubnet.contains(ipv6addr)); //
        System.out.println(ipv6addrsubnet + " contains " + ipv4mappedaddr + ": " + ipv6addrsubnet.contains(ipv4mappedaddr)); //

    } catch(AddressStringException e) {
        //e.getMessage has validation error
    }

output:

2001:db8::/32 contains 2001:db8:57ab::1 is true
2001:db8::/32 contains ::ffff:102:304 is false
查看更多
冷血范
3楼-- · 2019-02-08 12:55

org.apache.lenya.ac.IPRange appears to have these features.

The Apache Lenya project is an open-source content management system. It uses the Apache License, so you may be able to reuse just the code you need. (But as always, read the license yourself; don't trust legal advice from some guy on the internet! :-)

查看更多
Summer. ? 凉城
4楼-- · 2019-02-08 12:58

We developed a Java IPv4 arithmetic library ourselves. See it here: http://tufar.com/ipcalculator/ It is under BSD license.

查看更多
登录 后发表回答