All 15 Java Networking & HTTP Client questions
More in Java Networking & HTTP Client
Advertisement
Java › Java Networking & HTTP Client

How would you use InetAddress to perform DNS resolution (converting a hostname to an IP address) programmatically, and what's the difference between InetAddress.getByName() and getAllByName()?

Intermediate

Answer

InetAddress.getByName(hostname) resolves a hostname to a single IP address (returning the first one found if a hostname resolves to multiple addresses, common for load-balanced services), while getAllByName(hostname) returns an array of ALL IP addresses that hostname currently resolves to, useful for implementing custom client-side load balancing or failover logic across multiple backend IPs -- both perform an actual DNS lookup (a network operation, meaning it can throw UnknownHostException if resolution fails, and involves genuine latency, so results are often worth caching briefly rather than re-resolving on every single use).
try {
    InetAddress address = InetAddress.getByName("example.com");
    System.out.println(address.getHostAddress());  // e.g. "93.184.216.34"

    InetAddress[] allAddresses = InetAddress.getAllByName("example.com");
    for (InetAddress addr : allAddresses) {
        System.out.println(addr.getHostAddress());  // could print multiple IPs for a load-balanced service
    }
} catch (UnknownHostException e) {
    System.err.println("DNS resolution failed: " + e.getMessage());
}
Real-world example A custom client-side load balancer resolves a service's hostname using getAllByName() to discover all currently-advertised backend IP addresses, implementing its own round-robin distribution logic across them rather than relying purely on DNS's own (often simplistic, single-IP-per-query) round-robin behavior.

Common follow-ups: How does DNS caching (both at the OS level and within the JVM itself) affect how frequently a repeated getByName() call actually performs a fresh network lookup?;What's the security risk of DNS rebinding attacks, and how might an application need to defend against it?