I am looking for a package that is similar to Net_IPv4 and Net_IPv6 but written for Java. It needs to be able to do the following:
- Verify an address is valid (e.g. 127.0.0.1 is valid, 127.0.0.257 is not)
- Return if an address is contained within a subnet (e.g. 127.0.0.11 is in 127.0.0.0/28)
- Return the broadcast address for a given subnet (e.g. for 127.0.0.0/28 it's 127.0.0.15)
It would be awesome if it could also:
- Return a list of addresses for a subnet in order
- Sort a list of addresses
I could probably write a package to do all this, but if someone has already gone through the trouble and most likely has done a better job, I'm all about using that. Anyone know of such a package or packages that could do all this? We are expanding into IPv6, so it needs to work for both IPv4 and IPv6 if possible.
I appreciate any help.
The IPAddress Java library supports both IPv4 and IPv6 in a polymorphic manner including subnets. The javadoc is available at the link. Disclaimer: I am the project manager.
All the use cases you listed are supported for both IPv4 and Ipv6 transparently. In other words, it differs from most other utilities in the sense that the code below works identically with either IPv4 or IPv6 as the input strings.
Verify if an address is valid
Return if address is contained within a subnet
Return the broadcast address for a given subnet
Return a list of addresses for a subnet in order
Sort a list of addresses
Get set of subnetted networks and list of addresses (response to AhmedRana):
There can be a lot of addresses. The more efficient way to get the new subnets list is to use the prefix block iterator, which iterates through the prefix block subnets, as shown:
Maybe CIDRUtils can help you. It enables you to convert CIDR notation to an IP range.
Disclaimer: I am the author of CIDRUtils.
I'm the main contributor of commons-ip-math, an open-source Java library that offers a rich API for dealing with the most common calculations of IPv4, IPv6 and AS numbers. Although it has only been recently open sourced it has been battle-tested for years inside RIPE NCC. See how you can use it below.
(All the examples are working with similar syntax for IPv6 and AS numbers. Just use the Ipv6, Ipv6Range, Asn and AsnRange classes instead).
Although the library offers comparators for range types (e.g. comparing the size of subnets), there is no comparator for single addresses. However, it is fairly trivial to write your own since Ipv4, IPv6 and ASN types implement the Comparable interface:
It's only for IPv4, but the SubnetUtils class that is part of Commons Net has the functionality you are looking for. Based on that you could code up an IPv6 version and contribute it back to the project! :)
The InetAddress class, and related subclasses, would be a very good place to start: http://java.sun.com/j2se/1.4.2/docs/api/java/net/InetAddress.html