Networking in Java
Java provides rich networking capabilities through the java.net package, which covers TCP and UDP communication, URL handling, and HTTP connections. Networ...
Java Networking Fundamentals
Java provides rich networking capabilities through the java.net package, which covers TCP and UDP communication, URL handling, and HTTP connections. Networking in Java is designed around the same input/output stream model used for files, making it easy to apply familiar read/write patterns to network communication.
The InetAddress class represents an IP address and provides methods for hostname resolution. You can resolve a hostname to an IP address or look up the hostname for an IP. These operations involve DNS lookups, which are blocking and can take time, so they should always be performed on background threads:
InetAddress addr = InetAddress.getByName("www.example.com"); System.out.println(addr.getHostAddress()); // prints the IP address
The URL class represents a Uniform Resource Locator and provides a simple interface for making HTTP and HTTPS connections. By calling openConnection() on a URL, you get a URLConnection object that you can use to set request headers, write a request body, and read the response. For HTTPS connections, Java uses the system's default trust store to verify server certificates.
URL url = new URL("https://api.example.com/data"); URLConnection conn = url.openConnection(); InputStream in = conn.getInputStream();
Java 11 introduced the HttpClient API in java.net.http, which provides a modern, fluent interface for HTTP/1.1 and HTTP/2 communication. It supports asynchronous requests, WebSocket connections, and reactive stream integration, making it far superior to the older URLConnection for modern applications:
HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.example.com/data")) .GET().build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
The response object provides the status code, headers, and body as a String in this case, though the BodyHandlers class offers alternatives for byte arrays, streams, and file output.
Network programming requires careful attention to error handling. Connections can fail, time out, or be refused. Always set connection and read timeouts to prevent threads from blocking indefinitely on unresponsive remote services.
Interview tip: Explain the difference between URLConnection and HttpClient. URLConnection is the original Java API, verbose, and based on blocking I/O. HttpClient is modern, supports HTTP/2, allows both synchronous and asynchronous usage, and has a much cleaner API. Prefer HttpClient in all new Java 11+ code.
Working with URLs and HTTP
Handling URLs correctly is a common source of bugs in Java web applications. The URL and URI classes serve related but different purposes. URI is a more general concept that may or may not be resolvable over a network; URL is a type of URI that specifies a network-accessible resource. For parsing and manipulating addresses, prefer URI because it handles encoding correctly and does not perform DNS lookups on construction.
URL encoding converts characters that are not safe in URLs to percent-encoded form. Java's URLEncoder and URLDecoder classes handle this:
String encoded = URLEncoder.encode("hello world & more", "UTF-8"); // produces "hello+world+%26+more"
Note that URLEncoder uses + for spaces (form encoding) rather than %20. For path segments rather than query parameters, you need to encode spaces as %20 manually or use URI's multi-argument constructor, which handles encoding automatically.
Reading the response from an HTTP request requires properly closing streams to avoid resource leaks. Use try-with-resources:
try (InputStream in = new URL("https://example.com").openStream()) { String content = new String(in.readAllBytes(), StandardCharsets.UTF_8); System.out.println(content); }
HTTP connections involve a series of headers that control caching, authentication, content negotiation, and connection management. When using URLConnection, you set headers with setRequestProperty():
HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("Accept", "application/json"); conn.setRequestProperty("Authorization", "Bearer " + token);
For POST requests, you must call setDoOutput(true) and write to the connection's output stream before reading the response. Setting the correct Content-Type header tells the server how to parse the request body.
Connection pooling is automatic in the modern HttpClient, which reuses underlying TCP connections for multiple HTTP requests to the same host. This reduces latency significantly compared to establishing a new connection for each request.
Interview tip: When asked how to make an authenticated HTTP request in Java, walk through setting the Authorization header. Mention that credentials should never be hardcoded in source files, should be read from environment variables or a secrets manager, and that HTTPS must always be used to prevent credential interception.
DNS Resolution and Network Addresses
DNS resolution in Java translates human-readable hostnames into IP addresses that the network layer can route. The InetAddress class is the primary interface for address resolution and querying network interfaces. Understanding how Java performs DNS lookups, and the performance implications, is important for building reliable networked applications.
InetAddress.getByName() resolves a single address for a hostname. InetAddress.getAllByName() returns all IP addresses associated with a hostname, which is important for round-robin DNS where multiple servers share the same hostname for load balancing. Always handle the case where multiple addresses are returned by trying each in sequence if the first connection fails:
InetAddress[] addresses = InetAddress.getAllByName("api.example.com"); for (InetAddress addr : addresses) { System.out.println(addr.getHostAddress()); }
Java caches DNS results to avoid repeated lookups. The cache duration is controlled by the security property networkaddress.cache.ttl. By default, successful lookups are cached for 30 seconds and failed lookups for 10 seconds, though security-conscious configurations may cache indefinitely. In cloud environments where IP addresses change frequently, overly aggressive DNS caching can cause connections to be routed to decommissioned servers.
The NetworkInterface class lets you enumerate all network interfaces on the local machine and query their associated addresses. This is useful for service discovery in environments with multiple network cards or virtual interfaces:
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { NetworkInterface ni = interfaces.nextElement(); System.out.println(ni.getName() + ": " + ni.getInetAddresses()); }
IPv6 is fully supported in Java's networking APIs. InetAddress can return both Inet4Address and Inet6Address instances. If your application needs to bind to a specific address family, check the instance type. Java prefers IPv6 when both IPv4 and IPv6 are available, which can be overridden with the java.net.preferIPv4Stack system property.
Interview tip: Explain why DNS caching can cause problems in Kubernetes or cloud-native environments. Pod IP addresses change frequently when pods restart. If the JVM caches the old IP indefinitely, connections will fail until the cache expires or the application restarts. Setting a short TTL or disabling DNS caching is important in these environments.