I'd like to check in java if an IP address (IPv4, IPv6) is valid.
Google's guava library looks to me like a viable option. Its isInetAddress(String ipString)
method works just fine for IPv4 addresses. However for IPv6 addresses I'd have to use the isIsatapAddress(Inet6Address ip)
method.
The problem is that I want to use the args
from the void main(String []args)
to capture user's input and since the method requires a Inet6Address object I'm not sure how to do that.
InetAddresses.isInetAddress(String)
should work for both IPv4 and IPv6 addresses.
If you have also want to accept something like 2607:f0d0:1002:51::4/64
you could strip the netmask off with a little indexOf and substring, I don't think there's a method for that yet in Guava:
static boolean isInetAddressOrBlock(String address) {
int slash = address.lastIndexOf('/');
if (slash != -1) {
address = address.substring(0, slash);
}
return InetAddresses.isInetAddress(address);
}
If you considered using sun.net.util.IPAddressUtil
, don't -- sun.*
packages are implementation details of your JRE, not meant to be used and not available on all JREs.