Classify an address by version and scope without an instanceof check
Classify an address by version and scope without an instanceof check
Answer
InetAddress a = InetAddress.getByName(arg); System.out.println(a.getHostAddress() + (a.getAddress().length == 4 ? " IPv4" : " IPv6") + (a.isLoopbackAddress() ? " loopback" : "") + (a.isSiteLocalAddress() ? " site-local" : ""));
The byte count is the version test and it beats `instanceof Inet4Address`, which fails you on an address built from raw bytes. Every predicate here is a pure test on those bytes, so none of the four calls touches the network.
Harold 4e ch4 §The InetAddress Class; §The NetworkInterface Class