Determine if InetSocketAddress is IPv6 or IPv4

I need to determine if InetSocketAddressIPv6 or IPv4 is effective . The only thing I can do is either use the operator or check the length (which should return ). Both of them are less ideal ( slow, but should have made a copy of the array). instanceofgetAddress()byte[]instanceofgetAddress

Is there a better alternative?

+5
source share
4 answers

I don’t think you will find anything faster than instanceof. In this particular case, I expected the JIT compiler to optimize it to load and compare a pair of pointers; that is, about 5 machine instructions.

instanceof , , , .

instanceof , , ; .

+4

- . Inet4Address Inet6Address , .

Inet4Address.class == IPtoCheck.getClass();
Inet6Address.class == IPtoCheck.getClass();

, , instanceof, , Inet4 Inet6 .

+4

If you do not like it instanceof, you can try:

Inet4Address.class.isAssignableFrom(IPtoCheck);
Inet6Address.class.isAssignableFrom(IPtoCheck);

I do not think there is a faster solution than instanceofor higher.

+1
source

Compared to the overhead of creating InetAddress itself, with its implicit DNS overhead, the overhead if any of these are instanceoftrivial.

+1
source

All Articles