~/ learn/ comp-348/ cards/ Inspecting an address, and every address this host has
1 of 6

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

space flip · ← → navigate · esc to exit
NORMAL ~/memra/library/beb310b8-7a12-4793-a9f3-a09aa0335e53/flashcard utf-8 LF