Here are the most common and reliable ways to get hostnames and IP addresses in Java (Java 21). Pick the approach that matches your runtime (desktop app, server app, behind proxy, etc.).
- Quick local host info
- Good for simple cases, but can return 127.0.0.1 if your host isn’t configured in DNS/hosts.
import java.net.InetAddress; public class LocalHostQuick { public static void main(String[] args) throws Exception { InetAddress local = InetAddress.getLocalHost(); System.out.println("Host name: " + local.getHostName()); System.out.println("Canonical host name: " + local.getCanonicalHostName()); System.out.println("IP address: " + local.getHostAddress()); } } - Robust way: list network interfaces
- Picks non-loopback, non-virtual, up interfaces; prefers IPv4 but supports IPv6.
import java.net.Inet4Address; import java.net.InetAddress; import java.net.NetworkInterface; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; public class LocalAddresses { public static void main(String[] args) throws Exception { List<InetAddress> addresses = new ArrayList<>(); for (Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces(); ifaces.hasMoreElements(); ) { NetworkInterface nif = ifaces.nextElement(); if (!nif.isUp() || nif.isLoopback() || nif.isVirtual()) continue; for (Enumeration<InetAddress> addrs = nif.getInetAddresses(); addrs.hasMoreElements(); ) { InetAddress addr = addrs.nextElement(); if (addr.isLoopbackAddress() || addr.isLinkLocalAddress()) continue; // skip 127.0.0.1, fe80:: addresses.add(addr); } } // Prefer IPv4 for display addresses.stream() .sorted((a, b) -> Boolean.compare(b instanceof Inet4Address, a instanceof Inet4Address)) .forEach(a -> System.out.println(a.getHostAddress() + " (" + a.getHostName() + ")")); } } - DNS lookup: resolve a hostname to IPs
- Useful to get IPs for a remote host or reverse lookup a specific IP.
import java.net.InetAddress; public class ResolveHost { public static void main(String[] args) throws Exception { String host = "example.com"; // replace with your host InetAddress[] all = InetAddress.getAllByName(host); for (InetAddress inet : all) { System.out.println(host + " -> " + inet.getHostAddress()); } // Reverse lookup of a specific IP InetAddress ip = InetAddress.getByName("203.0.113.10"); // placeholder IP System.out.println(ip.getHostAddress() + " reverse -> " + ip.getCanonicalHostName()); } } - In a Spring MVC/Jakarta web app
- Getting the client IP (taking proxies into account) and server info. Utility to extract client IP (checks common proxy headers, then falls back):
import jakarta.servlet.http.HttpServletRequest; import java.util.List; public class IpUtils { private static final List<String> IP_HEADER_CANDIDATES = List.of( "X-Forwarded-For", "X-Real-IP", "CF-Connecting-IP", "Fastly-Client-Ip", "True-Client-Ip", "X-Cluster-Client-Ip", "Forwarded", "Forwarded-For" ); public static String getClientIp(HttpServletRequest request) { for (String header : IP_HEADER_CANDIDATES) { String value = request.getHeader(header); if (value != null && !value.isBlank() && !"unknown".equalsIgnoreCase(value)) { // X-Forwarded-For can contain a list: client, proxy1, proxy2... String first = value.split(",")[0].trim(); if (!first.isBlank()) return first; } } return request.getRemoteAddr(); } }
Controller example:
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.net.InetAddress;
import java.util.Map;
@RestController
public class NetInfoController {
@GetMapping("/net-info")
public Map<String, String> netInfo(HttpServletRequest request) throws Exception {
String clientIp = IpUtils.getClientIp(request);
// Server info via servlet and InetAddress
String serverIp = request.getLocalAddr(); // or request.getServerName()
String serverHostName = InetAddress.getLocalHost().getHostName();
return Map.of(
"clientIp", clientIp,
"serverIp", serverIp,
"serverHostName", serverHostName
);
}
}
Notes and tips
- getLocalHost may return 127.0.0.1 if your machine’s hostname isn’t resolvable. Enumerating NetworkInterface is more reliable.
- For containers/Kubernetes, you may prefer:
- The interface enumeration approach, or
- Reading an environment variable like HOSTNAME (if set by the platform).
- Reverse DNS (getCanonicalHostName) depends on network/DNS config and may be slow; cache if needed.
- Always handle exceptions: UnknownHostException, SocketException.
- When behind proxies/load balancers, only trust client-IP headers if your infrastructure sanitizes them; otherwise they can be spoofed.
