To resolve a hostname to an IP address (or vice versa) in Java, you use the java.net.InetAddress class. This class provides static factory methods to perform DNS lookups.
Here are the most common ways to use it:
1. Resolve a Hostname to an IP Address
Use InetAddress.getByName(String host) to get the primary IP address associated with a domain.
package org.kodejava.net;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class ResolveHost {
public static void main(String[] args) {
try {
// Resolve a domain name to its IP address
InetAddress address = InetAddress.getByName("www.google.com");
System.out.println("Host Name: " + address.getHostName());
System.out.println("IP Address: " + address.getHostAddress());
} catch (UnknownHostException e) {
System.err.println("Could not resolve host: " + e.getMessage());
}
}
}
2. Resolve All IP Addresses for a Host
Large websites often have multiple IP addresses for load balancing. You can retrieve all of them using getAllByName(String host).
try {
InetAddress[] addresses = InetAddress.getAllByName("www.google.com");
for (InetAddress addr : addresses) {
System.out.println(addr.getHostAddress());
}
} catch (UnknownHostException e) {
e.printStackTrace();
}
3. Reverse DNS Lookup (IP to Hostname)
If you have an IP address and want to find the hostname, use getByName() with the IP string and then call getHostName().
try {
InetAddress address = InetAddress.getByName("8.8.8.8");
// This triggers a reverse DNS lookup
System.out.println("The hostname for 8.8.8.8 is: " + address.getHostName());
} catch (UnknownHostException e) {
e.printStackTrace();
}
Key Methods Summary:
getHostAddress(): Returns the IP address string in textual presentation (e.g., “142.250.190.36”).getHostName(): Returns the hostname for this IP address. If the operation is successful, it will perform a reverse lookup.getCanonicalHostName(): Returns the fully qualified domain name (FQDN).
Important Note on Exceptions
Always wrap these calls in a try-catch block for UnknownHostException. This exception is thrown if the DNS server cannot find the host or if the network is unreachable.
