Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A good Java library for network math [closed]

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?

like image 471
Loren_ Avatar asked Oct 20 '08 22:10

Loren_


3 Answers

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

like image 50
Nicolai Tufar Avatar answered Nov 15 '22 07:11

Nicolai Tufar


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! :-)

like image 26
Bill Karwin Avatar answered Nov 15 '22 08:11

Bill Karwin


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
like image 2
Sean F Avatar answered Nov 15 '22 06:11

Sean F