InetAddress
Before your Java program can open a socket or fetch a URL, it needs to know where to connect — and that means turning a hostname like "example.com" into a numeric IP address. The java.net.InetAddress class is Java’s built-in tool for that job: it wraps an IP address (v4 or v6) together with the hostname it came from, and provides factory methods for forward and reverse DNS lookups.
What Is InetAddress?
InetAddress lives in the java.net package and represents a single IP address, optionally paired with the hostname it was resolved from. Because IP exists in two flavors, Java provides two concrete subclasses:
| Class | Represents | Example address |
|---|---|---|
Inet4Address | 32-bit IPv4 address | 93.184.216.34 |
Inet6Address | 128-bit IPv6 address | 2606:2800:220:1:248:1893:25c8:1946 |
You rarely instantiate these directly. Instead you call one of InetAddress’s static factory methods.
Note:
InetAddresshas no public constructor. All instances are obtained via the static factory methods described below.
Getting an InetAddress
By hostname (forward DNS lookup)
import java.net.InetAddress;
import java.net.UnknownHostException;
public class ForwardLookup {
public static void main(String[] args) throws UnknownHostException {
InetAddress address = InetAddress.getByName("example.com");
System.out.println("Host name : " + address.getHostName());
System.out.println("IP address: " + address.getHostAddress());
System.out.println("Is reachable (2 s): " + address.isReachable(2000));
}
}
Host name : example.com
IP address: 93.184.216.34
Is reachable (2 s): true
getByName() throws UnknownHostException (a checked exception) when the name cannot be resolved, so you must handle or declare it.
All addresses for a hostname
Some hostnames map to multiple IPs (for load-balancing or redundancy). Use getAllByName() to retrieve them all:
import java.net.InetAddress;
import java.net.UnknownHostException;
public class AllAddresses {
public static void main(String[] args) throws UnknownHostException {
InetAddress[] addresses = InetAddress.getAllByName("google.com");
for (InetAddress addr : addresses) {
System.out.println(addr.getHostAddress());
}
}
}
142.250.185.46
2a00:1450:4009:81e::200e
By raw IP address bytes
If you already have the numeric address you can bypass DNS entirely:
import java.net.InetAddress;
import java.net.UnknownHostException;
public class ByRawBytes {
public static void main(String[] args) throws UnknownHostException {
// 4 bytes for IPv4: 8.8.8.8 (Google's public DNS)
byte[] raw = { 8, 8, 8, 8 };
InetAddress addr = InetAddress.getByAddress(raw);
System.out.println(addr.getHostAddress()); // 8.8.8.8
}
}
8.8.8.8
Tip: Passing a byte array to
getByAddress()performs no DNS lookup — it’s instantaneous and can never throwUnknownHostExceptionfor a “not found” reason (though it still throws it if the array length is wrong).
Local machine address
import java.net.InetAddress;
import java.net.UnknownHostException;
public class LocalHost {
public static void main(String[] args) throws UnknownHostException {
InetAddress local = InetAddress.getLocalHost();
System.out.println("Hostname: " + local.getHostName());
System.out.println("IP : " + local.getHostAddress());
}
}
Hostname: my-laptop.local
IP : 192.168.1.42
Loopback address
For testing you can get the loopback address without any DNS call:
InetAddress loopback = InetAddress.getLoopbackAddress();
System.out.println(loopback.getHostAddress()); // 127.0.0.1
Reverse DNS Lookup
A reverse lookup maps an IP address back to a hostname. In InetAddress, the getHostName() method performs the reverse lookup lazily the first time you call it (if the object was created from raw bytes or a numeric string):
import java.net.InetAddress;
import java.net.UnknownHostException;
public class ReverseLookup {
public static void main(String[] args) throws UnknownHostException {
// Create from numeric string — no lookup happens yet
InetAddress addr = InetAddress.getByName("8.8.8.8");
// This triggers the reverse DNS query
System.out.println(addr.getHostName()); // dns.google
}
}
dns.google
If no PTR record exists, getHostName() simply returns the numeric IP string — it never throws.
Useful Instance Methods
| Method | Returns | Notes |
|---|---|---|
getHostName() | String | Hostname; triggers reverse lookup if needed |
getHostAddress() | String | Numeric IP string (“93.184.216.34”) |
getAddress() | byte[] | Raw address bytes (4 or 16 bytes) |
isReachable(int timeout) | boolean | ICMP ping or TCP port 7; needs network |
isLoopbackAddress() | boolean | True for 127.x.x.x / ::1 |
isSiteLocalAddress() | boolean | True for RFC-1918 private ranges |
isMulticastAddress() | boolean | True for 224.0.0.0/4 or ff00::/8 |
isAnyLocalAddress() | boolean | True for 0.0.0.0 / :: (wildcard) |
import java.net.InetAddress;
import java.net.UnknownHostException;
public class AddressChecks {
public static void main(String[] args) throws UnknownHostException {
InetAddress addr = InetAddress.getByName("192.168.0.1");
System.out.println("Site-local : " + addr.isSiteLocalAddress()); // true
System.out.println("Loopback : " + addr.isLoopbackAddress()); // false
System.out.println("Multicast : " + addr.isMulticastAddress()); // false
}
}
Site-local : true
Loopback : false
Multicast : false
Checking IPv4 vs IPv6
Since Inet4Address and Inet6Address are both subclasses of InetAddress, you can check the type with instanceof:
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class IpVersionCheck {
public static void main(String[] args) throws UnknownHostException {
InetAddress addr = InetAddress.getByName("::1");
if (addr instanceof Inet6Address) {
System.out.println("IPv6 address detected");
} else if (addr instanceof Inet4Address) {
System.out.println("IPv4 address detected");
}
}
}
IPv6 address detected
Practical Example: Simple Network Utility
Here is a small utility that prints all resolved addresses for a host and flags any that belong to private ranges:
import java.net.InetAddress;
import java.net.UnknownHostException;
public class NetworkInfo {
public static void main(String[] args) throws UnknownHostException {
String host = "google.com";
InetAddress[] addresses = InetAddress.getAllByName(host);
System.out.println("Addresses for: " + host);
for (InetAddress addr : addresses) {
String type = addr.isSiteLocalAddress() ? "private" : "public";
String version = (addr.getAddress().length == 4) ? "IPv4" : "IPv6";
System.out.printf(" %-40s [%s, %s]%n",
addr.getHostAddress(), version, type);
}
}
}
Addresses for: google.com
142.250.185.46 [IPv4, public]
2a00:1450:4009:81e::200e [IPv6, public]
Under the Hood
When you call InetAddress.getByName("example.com"), the JVM does not reinvent DNS — it delegates to the operating system’s resolver, which follows the usual lookup chain:
- Hosts file —
/etc/hostson Linux/macOS,C:\Windows\System32\drivers\etc\hostson Windows. - Local DNS cache — the OS caches recent answers, so repeated calls may not hit the network.
- Configured DNS server — your router, ISP, or corporate DNS (e.g.,
8.8.8.8).
JVM-level caching sits on top of that. The JVM caches successful lookups for 30 seconds by default (controlled by the security property networkaddress.cache.ttl). Failed lookups are cached for 10 seconds (networkaddress.cache.negative.ttl). In security-sensitive environments — such as when a SecurityManager is active — positive results are cached forever to prevent DNS-rebinding attacks.
Warning: Long-lived caching can cause issues in cloud or container environments where IP addresses change frequently. You can tune caching via
java.securityproperties, but be careful about the security trade-offs.
isReachable() is worth understanding too. It first tries ICMP echo (ping). If the JVM lacks the necessary OS permissions (common on non-root processes), it falls back to attempting a TCP connection to port 7. Many hosts block both, so a false result does not necessarily mean the host is down — it may just mean pings are firewalled.
The raw getAddress() byte array is stored in network byte order (big-endian), which matches the standard Java int representation and the wire format used in protocols like TCP/IP.
InetAddress and Sockets
You will typically feed an InetAddress directly into a socket or URL constructor rather than printing it:
import java.net.InetAddress;
import java.net.Socket;
public class ConnectByAddress {
public static void main(String[] args) throws Exception {
InetAddress server = InetAddress.getByName("example.com");
try (Socket socket = new Socket(server, 80)) {
System.out.println("Connected to: " + socket.getInetAddress().getHostAddress());
}
}
}
Connected to: 93.184.216.34
This pattern separates the DNS resolution step from the connection step, which is useful when you want to resolve once and reuse the address for multiple connections — avoiding repeated DNS queries.
Tip: For more advanced use cases such as connecting through a proxy, setting bind addresses, or non-blocking I/O, look at
java.net.InetSocketAddress, which pairs anInetAddresswith a port number into a single object accepted bySocketChannelandServerSocketChannel.
Related Topics
- Socket Programming — use
InetAddressto open TCP connections to a resolved host - URL Class — higher-level networking that internally uses
InetAddressfor resolution - URLConnection — open a connection to a URL and read its content
- HttpURLConnection — make HTTP GET/POST requests without a third-party library
- Networking Basics — overview of Java’s networking model and
java.netpackage