Reputation: 617
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.
Upvotes: 1
Views: 595
Reputation: 9980
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.
Upvotes: 3
Reputation: 29959
There is a catch, just checking for :
is not enough if you use InetAddress
.
An address of the pattern ::ffff:<IPv4 Address>
is considered IPv4 address. For example, the following call returns an Inet4Address
:
InetAddress.getByName("::ffff:1.2.3.4")
The same is true for all variants of the same address, like ::0:ffff:1.2.3.4
.
From the documentation of Inet6Address:
IPv4-mapped address
Of the form::ffff:w.x.y.z, this IPv6 address is used to represent an IPv4 address. It allows the native program to use the same address data structure and also the same socket when communicating with both IPv4 and IPv6 nodes.In InetAddress and Inet6Address, it is used for internal representation; it has no functional role. Java will never return an IPv4-mapped address. These classes can take an IPv4-mapped address as input, both in byte array and text representation. However, it will be converted into an IPv4 address.
This seems to be the only exception though.
Upvotes: 3