// Get the IP address for a hostname InetAddress address = InetAddress.getByName("www.google.com"); // Get the canonical hostname associated with the IP address String canonicalHostname = address.getCanonicalHostName(); System.out.println("The canonical hostname for " + address.getHostAddress() + " is " + canonicalHostname);
// Get the IP address for the local host InetAddress address = InetAddress.getLocalHost(); // Get the canonical hostname associated with the IP address String canonicalHostname = address.getCanonicalHostName(); System.out.println("The canonical hostname for " + address.getHostAddress() + " is " + canonicalHostname);Output: The canonical hostname for 192.168.1.2 is DESKTOP-ABC123 This example gets the IP address for the local host using the getLocalHost() method and then uses the getCanonicalHostName() method to retrieve the canonical hostname associated with that IP address. The InetAddress class is part of the java.net package library.