Search code examples
javaipv6

Is ":" in a valid IP string sufficient to determine it is an IPv6 address?


Given a string that is 100% unequivocally a valid IP address.

However, the method receiving it as a parameter does not receive an additional parameter telling it whether it is an IPv4 or IPv6.

I have seen a way to determine whether an IPv4 or IPv6:

InetAddress address = InetAddress.getByName(ip);
if (address instanceof Inet6Address) {
    // It's ipv6
} else if (address instanceof Inet4Address) {
    // It's ipv4
}

But I am looking for a speedier way (note that the above should also be surrounded with a try/catch).

Can I get away with something as simple as:

if (totallyValidIp.contains(":") {
        // It's ipv6
}
else {
        // It's ipv4
}

or is there a catch of which I am not aware? (e.g. valid IPv6 that does not contain any ":").

Note: This "optimization" is counting on the fact that I know a-priory that the IP string is an already checked and validated IP address.


Solution

  • An IPv6 address string will contain between two and seven colons, not necessarily contiguous. But if you already validated the address elsewhere, then checking for the presence of a colon ought to be sufficient.

    But if you already have an InetAddress object, just stick with instanceof. Converting back and forth to string sounds like a lot of unnecessary work.