It's not as simple as it might seem, there are some ambiguities around characters, such as hyphens, underscores, and square brackets '-', '_', '[]'.
The Java SDK has some limitations in this area. When using InetAddress.getByName, it will go online to resolve DNS names and resolve an address that is expensive and unnecessary if all you want is to determine the host address and address. In addition, if the address is written in a slightly different but valid format (common in IPv6), then string comparisons based on the results of InetAddress.getByName will not work.
The Java IPAddress library will do this. Javadoc is available here. Disclaimer: I am the project manager.
static void check(HostName host) { try { host.validate(); if(host.isAddress()) { System.out.println("address: " + host.asAddress()); } else { System.out.println("host name: " + host); } } catch(HostNameException e) { System.out.println(e.getMessage()); } } public static void main(String[] args) { HostName host = new HostName("1.2.3.4"); check(host); host = new HostName("1.2.a.4"); check(host); host = new HostName("::1"); check(host); host = new HostName("[::1]"); check(host); host = new HostName("1.2.?.4"); check(host); }
Output:
address: 1.2.3.4 host name: 1.2.a.4 address: ::1 address: ::1 1.2.?.4 Host error: invalid character at index 4
source share