Getting the Hostname of an IP Address

This example attempts to retrieve the hostname for an IP address. Note that getHostName() may not succeed, in which case it simply returns the IP address.
try { // Get hostname by textual representation of IP address InetAddress addr = InetAddress.getByName("127.0.0.1"); // Get hostname by a byte array containing the IP address byte[] ipAddr = new byte[]{127, 0, 0, 1}; addr = InetAddress.getByAddress(ipAddr); // Get the host name String hostname = addr.getHostName(); // Get canonical host name String hostnameCanonical = addr.getCanonicalHostName(); } catch (UnknownHostException e) { }

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.