Accept either a URL or a bare IP address as the first argument
Accept either a URL or a bare IP address as the first argument
Answer
URL target; try { target = new URL(arg); } catch (MalformedURLException ex) { InetAddress host = InetAddress.getByName(arg); target = new URL("http://" + host.getHostAddress() + "/"); }
The specific interpretation is tried first; only its failure means the argument might be an address. getByName parses a dotted-quad without a lookup and does a DNS query for a name, throwing UnknownHostException — so the enclosing method declares throws IOException and both failures surface as one.
Harold 4e ch7 §Reading Data from a Server; ch5 §The URL Class; ch4 §The InetAddress Class