~/ learn/ comp-348/ cards/ InetAddress: resolving names and addresses
1 of 5

Resolve a host to every address it has, and handle the checked failure

Resolve a host to every address it has, and handle the checked failure

Answer

try { for (InetAddress a : InetAddress.getAllByName(host)) { System.out.println(a.getHostName() + " -> " + a.getHostAddress()); } } catch (UnknownHostException ex) { System.err.println("no such host: " + host); }

`getAllByName` returns the whole array because one name commonly maps to several addresses; `getByName` would silently pick one of them for you. `UnknownHostException` is checked (it extends `IOException`), so the compiler will not let you forget that a lookup can fail.

Harold 4e ch4 §The InetAddress Class

space flip · ← → navigate · esc to exit
NORMAL ~/memra/library/71324384-7126-4b0c-8d72-7da21336b971/flashcard utf-8 LF