Java Networking Basics
Java networking is how a Java program talks to other programs over a network: a browser asking a web server for a page, a mobile app calling a REST API, or a game client sending moves to a server. The java.net and java.net.http packages give you everything you need, from IP addresses and ports to TCP sockets, UDP packets and a full HTTP client.
This lesson explains the core ideas behind networking in Java (IP addresses, ports, TCP, UDP and HTTP) and shows each one with a small program you can run on your own computer, without an internet connection.
How Computers Talk: Key Networking Terms
Before writing code, it helps to know the words that every networking API uses.
| Term | Meaning | Example |
|---|---|---|
| Host | A computer or device on a network | localhost, api.example.com |
| IP address | The numeric address of a host | 127.0.0.1 (IPv4), ::1 (IPv6) |
| DNS | The system that turns host names into IP addresses | example.com → 93.184.215.14 |
| Port | A number (0–65535) that identifies one program on a host | 80 for HTTP, 443 for HTTPS |
| Socket | One end of a two-way connection: IP address + port | 127.0.0.1:5000 |
| Protocol | The rules both sides follow | TCP, UDP, HTTP |
| Client | The program that starts the conversation | A browser, a Java HttpClient |
| Server | The program that waits for clients | A web server listening on port 8080 |
localhost (IP 127.0.0.1) is the loopback address: it always means "this same computer". Every example in this lesson uses it, so the client and server run on your machine.
The Java Networking Packages
Java splits networking into a few classes, each for a different level of detail.
| Class | Package | Use it to |
|---|---|---|
InetAddress | java.net | Represent an IP address and look up host names |
InetSocketAddress | java.net | Combine an IP address (or host name) with a port |
URI, URL | java.net | Represent web addresses like https://example.com/docs |
Socket, ServerSocket | java.net | Open TCP connections (client and server) |
DatagramSocket, DatagramPacket | java.net | Send and receive UDP packets |
HttpClient, HttpRequest, HttpResponse | java.net.http | Send HTTP requests (Java 11+) |
The rest of this lesson gives you a first look at each group. Later lessons cover the Java URL class, the Java URI class and the Java HttpClient in full detail.
Working with IP Addresses: InetAddress
InetAddress represents an IP address. You never call new InetAddress(); instead, you use static factory methods.
| Method | What it returns |
|---|---|
InetAddress.getLoopbackAddress() | The loopback address (localhost) |
InetAddress.getByName(String host) | The address for a host name or an IP literal |
InetAddress.getAllByName(String host) | Every address of a host (it may have several) |
InetAddress.getLocalHost() | The address of this computer on its network |
import java.net.InetAddress;
import java.net.UnknownHostException;
public class InetAddressDemo {
public static void main(String[] args) throws UnknownHostException {
// The loopback address always points to "this computer"
InetAddress loopback = InetAddress.getLoopbackAddress();
System.out.println("Loopback host name : " + loopback.getHostName());
System.out.println("Loopback IP address: " + loopback.getHostAddress());
System.out.println("Is loopback? : " + loopback.isLoopbackAddress());
// An IP literal is parsed directly, so no DNS lookup is needed
InetAddress router = InetAddress.getByName("192.168.1.1");
System.out.println("Router address : " + router.getHostAddress());
System.out.println("Private LAN? : " + router.isSiteLocalAddress());
// IPv6 literals work the same way
InetAddress ipv6Loopback = InetAddress.getByName("::1");
System.out.println("IPv6 loopback : " + ipv6Loopback.getHostAddress()
+ " (" + ipv6Loopback.getClass().getSimpleName() + ")");
}
}
Output:
Loopback host name : localhost
Loopback IP address: 127.0.0.1
Is loopback? : true
Router address : 192.168.1.1
Private LAN? : true
IPv6 loopback : 0:0:0:0:0:0:0:1 (Inet6Address)
How it works:
getHostName()returns the name andgetHostAddress()returns the numeric address as text.- When you pass an IP literal such as
"192.168.1.1"togetByName(), Java only checks its format; it does not contact a DNS server. isSiteLocalAddress()istruefor private network ranges such as192.168.x.xand10.x.x.x, which are used inside homes and offices.- IPv4 addresses are
Inet4Addressobjects and IPv6 addresses areInet6Addressobjects. Java prints IPv6 addresses in their full form, so::1appears as0:0:0:0:0:0:0:1.
Looking Up Host Names with DNS
When you pass a host name to getByName(), Java asks DNS for its address. If the name cannot be found, the method throws UnknownHostException.
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
public class HostLookup {
public static void main(String[] args) {
String[] hosts = {"localhost", "no-such-server.invalid"};
for (String host : hosts) {
try {
InetAddress[] addresses = InetAddress.getAllByName(host);
String ips = Arrays.stream(addresses)
.map(InetAddress::getHostAddress)
.sorted()
.toList()
.toString();
System.out.println(host + " -> " + ips);
} catch (UnknownHostException e) {
System.out.println(host + " -> unknown host");
}
}
}
}
Output (the localhost line can differ if your system lists only IPv4 or only IPv6):
localhost -> [127.0.0.1]
no-such-server.invalid -> unknown host
How it works:
getAllByName()returns every address of a host. Big sites often have several, for load balancing and IPv6.- The
.invalidtop-level domain is reserved and never resolves, so the second lookup always fails withUnknownHostException. - A real host name such as
www.example.comworks the same way, but needs a working internet connection and DNS server.
Note: DNS lookups can be slow and can fail. Always handle
UnknownHostException, and avoid looking up the same name in a tight loop; the JVM caches successful lookups for a short time.
Ports and Socket Addresses: InetSocketAddress
An IP address finds a computer; a port finds a program on that computer. One server can run a web server on port 80, a database on port 5432 and an SSH server on port 22 at the same time.
| Port | Common service |
|---|---|
| 22 | SSH |
| 25 | SMTP (email) |
| 80 | HTTP |
| 443 | HTTPS |
| 3306 | MySQL |
| 5432 | PostgreSQL |
| 8080 | Development web servers |
Ports 0–1023 are "well-known" ports and usually need administrator rights to open. Your own servers normally use ports above 1023. InetSocketAddress combines a host and a port into one object.
import java.net.InetSocketAddress;
public class SocketAddressDemo {
public static void main(String[] args) {
// Resolved: Java looks up the host name immediately
InetSocketAddress devServer = new InetSocketAddress("localhost", 8080);
System.out.println("Host : " + devServer.getHostString());
System.out.println("Port : " + devServer.getPort());
System.out.println("IP : " + devServer.getAddress().getHostAddress());
System.out.println("Unresolved: " + devServer.isUnresolved());
// Unresolved: no DNS lookup now; useful for proxies and lazy lookups
InetSocketAddress api = InetSocketAddress.createUnresolved("api.example.com", 443);
System.out.println("API : " + api.getHostString() + ":" + api.getPort()
+ " (unresolved = " + api.isUnresolved() + ")");
// Port numbers must be between 0 and 65535
try {
new InetSocketAddress("localhost", 70000);
} catch (IllegalArgumentException e) {
System.out.println("Error : " + e.getMessage());
}
}
}
Output:
Host : localhost
Port : 8080
IP : 127.0.0.1
Unresolved: false
API : api.example.com:443 (unresolved = true)
Error : port out of range:70000
How it works:
- The
InetSocketAddress(String, int)constructor resolves the host name right away, sogetAddress()returns its IP. createUnresolved()stores only the name and port. The lookup happens later, for example on the other side of a proxy.- Any port outside 0–65535 is rejected with
IllegalArgumentException.
TCP vs UDP in Java
The two main transport protocols behave very differently, and Java has separate classes for each.
| TCP | UDP | |
|---|---|---|
| Connection | Yes, both sides connect first | No, packets are just sent |
| Delivery | Guaranteed, in order | Not guaranteed, may arrive out of order |
| Data | A continuous stream of bytes | Separate packets (datagrams) |
| Speed | A little slower (extra checks) | Faster, less overhead |
| Java classes | Socket, ServerSocket | DatagramSocket, DatagramPacket |
| Used by | HTTP, email, databases, file transfer | Video calls, online games, DNS |
A TCP Client and Server in Java
With TCP, a server opens a ServerSocket on a port and waits with accept(). A client creates a Socket to that host and port. Once connected, both sides read and write through ordinary input and output streams.
This program runs both sides: the server on a virtual thread, the client in main. The server turns every line it receives into upper case and sends it back.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class TcpEchoDemo {
static final int PORT = 5000;
public static void main(String[] args) throws Exception {
// 1. Server: listen on localhost:5000
ServerSocket serverSocket = new ServerSocket(PORT, 50, InetAddress.getLoopbackAddress());
Thread server = Thread.startVirtualThread(() -> {
try (Socket client = serverSocket.accept(); // wait for one client
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
PrintWriter out = new PrintWriter(client.getOutputStream(), true)) {
String line;
while ((line = in.readLine()) != null) {
if (line.equals("bye")) {
out.println("GOODBYE");
break;
}
out.println(line.toUpperCase()); // reply to the client
}
} catch (Exception e) {
System.out.println("Server error: " + e.getMessage());
}
});
// 2. Client: connect, send three lines, print each reply
try (Socket socket = new Socket("localhost", PORT);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {
System.out.println("Connected to " + socket.getRemoteSocketAddress());
for (String message : new String[]{"hello server", "java networking", "bye"}) {
out.println(message);
System.out.println("sent: " + message + " | reply: " + in.readLine());
}
}
server.join();
serverSocket.close();
}
}
Output:
Connected to localhost/127.0.0.1:5000
sent: hello server | reply: HELLO SERVER
sent: java networking | reply: JAVA NETWORKING
sent: bye | reply: GOODBYE
How it works:
new ServerSocket(PORT, 50, InetAddress.getLoopbackAddress())listens on port 5000, only onlocalhost. The50is the size of the queue of waiting connections.serverSocket.accept()blocks until a client connects, then returns aSocketfor that one client.new Socket("localhost", PORT)connects the client. The connection is now open in both directions.- Both sides wrap the socket streams:
PrintWriterwith auto-flush to send lines,BufferedReaderto read lines. - try-with-resources closes the sockets automatically. Closing a socket ends the connection for both sides.
Note: If nothing is listening on the port,
new Socket(...)throwsjava.net.ConnectException: Connection refused. If the port is already in use,new ServerSocket(...)throwsjava.net.BindException.
Sending a UDP Packet in Java
UDP has no connection. A sender wraps bytes in a DatagramPacket with the destination address and port, and a receiver waits for packets on its own DatagramSocket.
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.charset.StandardCharsets;
public class UdpDemo {
public static void main(String[] args) throws Exception {
InetAddress localhost = InetAddress.getLoopbackAddress();
try (DatagramSocket receiver = new DatagramSocket(5001, localhost);
DatagramSocket sender = new DatagramSocket()) { // any free port
// Send one packet to localhost:5001
byte[] data = "temperature=24.5".getBytes(StandardCharsets.UTF_8);
sender.send(new DatagramPacket(data, data.length, localhost, 5001));
// Receive it: the buffer must be big enough for the packet
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
receiver.setSoTimeout(2000); // wait at most 2 seconds
receiver.receive(packet);
String message = new String(packet.getData(), 0, packet.getLength(), StandardCharsets.UTF_8);
System.out.println("Received " + packet.getLength() + " bytes: " + message);
System.out.println("From the same host? " + packet.getAddress().isLoopbackAddress());
}
}
}
Output:
Received 16 bytes: temperature=24.5
From the same host? true
How it works:
- The receiver is bound to port 5001. The sender uses
new DatagramSocket(), which picks any free port. send()returns immediately; UDP does not wait for the receiver to confirm anything.receive()fills the buffer and setsgetLength()to the real packet size, so the code converts only that many bytes to text.setSoTimeout(2000)stopsreceive()from waiting forever. Without it, a lost packet would block the program.
HTTP: Networking on Top of TCP
Most programs today do not use raw sockets. They use HTTP, a text protocol that runs on top of TCP. A client sends a request (a method such as GET or POST, a path and headers), and the server sends back a response (a status code, headers and a body).
| Part | Example |
|---|---|
| Request line | GET /hello?name=Asha HTTP/1.1 |
| Request headers | Host: localhost:8080, Accept: text/plain |
| Status code | 200 OK, 404 Not Found, 500 Server Error |
| Response headers | Content-Type: text/plain |
| Response body | Hello, Asha! |
The JDK includes a small HTTP server (com.sun.net.httpserver.HttpServer) for tests and demos, and the HttpClient for sending requests.
import com.sun.net.httpserver.HttpServer;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
public class HttpBasicsDemo {
public static void main(String[] args) throws Exception {
// A tiny HTTP server on localhost:8080
HttpServer server = HttpServer.create(new InetSocketAddress("localhost", 8080), 0);
server.createContext("/hello", exchange -> {
String query = exchange.getRequestURI().getQuery(); // "name=Asha"
String name = query == null ? "World" : query.split("=")[1];
byte[] body = ("Hello, " + name + "!").getBytes(StandardCharsets.UTF_8);
exchange.getResponseHeaders().add("Content-Type", "text/plain");
exchange.sendResponseHeaders(200, body.length);
exchange.getResponseBody().write(body);
exchange.close();
});
server.start();
// The client sends a GET request and prints the response
try (HttpClient client = HttpClient.newHttpClient()) {
HttpRequest request = HttpRequest.newBuilder(URI.create("http://localhost:8080/hello?name=Asha")).build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println("Status : " + response.statusCode());
System.out.println("Content-Type: " + response.headers().firstValue("Content-Type").orElse("?"));
System.out.println("Body : " + response.body());
} finally {
server.stop(0);
}
}
}
Output:
Status : 200
Content-Type: text/plain
Body : Hello, Asha!
How it works:
HttpServer.create(...)opens a TCP server on port 8080, andcreateContext("/hello", handler)runs the handler for every request whose path starts with/hello.- In the handler,
sendResponseHeaders(200, length)sends the status line and headers; the body is then written togetResponseBody(). - On the client side,
HttpRequestdescribes the request andclient.send(...)returns anHttpResponsewith the status, headers and body. HttpClientimplementsAutoCloseablesince Java 21, so try-with-resources shuts it down cleanly.
Note:
com.sun.net.httpserveris fine for learning, tests and small tools. Real web applications use servers such as Tomcat, Jetty or frameworks like Spring Boot.
Setting Connection Timeouts
Networks are unreliable: a server may be down, slow or unreachable. By default, some operations wait a very long time. Always set timeouts so your program can react.
| Timeout | Set with | Protects against |
|---|---|---|
| Connect timeout | socket.connect(address, millis) | A host that never answers the connection |
| Read timeout | socket.setSoTimeout(millis) | A server that connects but never sends data |
| HTTP connect timeout | HttpClient.newBuilder().connectTimeout(Duration) | Slow HTTP connections |
| HTTP request timeout | HttpRequest.newBuilder().timeout(Duration) | Slow HTTP responses |
import java.io.InputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
public class TimeoutDemo {
public static void main(String[] args) throws Exception {
// A "silent" server: it accepts connections but never sends anything
try (ServerSocket silentServer = new ServerSocket(5002, 50, InetAddress.getLoopbackAddress());
Socket socket = new Socket()) {
socket.connect(new InetSocketAddress("localhost", 5002), 1000); // connect timeout: 1 s
socket.setSoTimeout(500); // read timeout: 0.5 s
System.out.println("Connected, waiting for data...");
InputStream in = socket.getInputStream();
try {
in.read(); // blocks until data or timeout
} catch (SocketTimeoutException e) {
System.out.println("Gave up: " + e.getMessage());
}
}
}
}
Output:
Connected, waiting for data...
Gave up: Read timed out
How it works:
new Socket()creates an unconnected socket, so you can pass a connect timeout toconnect(address, 1000).- The server never writes, so
in.read()would block forever.setSoTimeout(500)makes it throwSocketTimeoutExceptionafter half a second instead. - The connection itself succeeds because the operating system accepts it into the server's queue, even before the server calls
accept().
Real-World Example: A Service Health Checker
Operations teams often need a quick answer to "which of my services are up?". This program checks a list of services by opening a TCP connection to each host and port with a short timeout. It starts two local servers to stand in for a database and a cache, and leaves a third port closed, so you can run it anywhere.
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class HealthChecker {
record Service(String name, String host, int port) { }
record Result(Service service, boolean up, String detail) { }
// Try to open a TCP connection; success means something is listening
static Result check(Service service, int timeoutMillis) {
try (Socket socket = new Socket()) {
socket.connect(new InetSocketAddress(service.host(), service.port()), timeoutMillis);
return new Result(service, true, "accepting connections");
} catch (IOException e) {
return new Result(service, false, e.getClass().getSimpleName());
}
}
public static void main(String[] args) throws Exception {
InetAddress localhost = InetAddress.getLoopbackAddress();
// Stand-ins for real services: only these two ports are open
try (ServerSocket fakeDatabase = new ServerSocket(6001, 50, localhost);
ServerSocket fakeCache = new ServerSocket(6002, 50, localhost)) {
List<Service> services = List.of(
new Service("orders-db", "localhost", 6001),
new Service("session-cache", "localhost", 6002),
new Service("search-engine", "localhost", 6003),
new Service("payments-api", "no-such-server.invalid", 443));
// Check all services at the same time, one virtual thread each
List<Future<Result>> futures = new ArrayList<>();
try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
for (Service service : services) {
futures.add(executor.submit(() -> check(service, 1000)));
}
}
int upCount = 0;
for (Future<Result> future : futures) {
Result result = future.get();
Service s = result.service();
System.out.printf("%-14s %-27s %-5s %s%n", s.name(), s.host() + ":" + s.port(),
result.up() ? "UP" : "DOWN", result.detail());
if (result.up()) upCount++;
}
System.out.println(upCount + " of " + services.size() + " services are up");
}
}
}
Output:
orders-db localhost:6001 UP accepting connections
session-cache localhost:6002 UP accepting connections
search-engine localhost:6003 DOWN ConnectException
payments-api no-such-server.invalid:443 DOWN UnknownHostException
2 of 4 services are up
How it works:
- Describing services. A
Servicerecord holds a name, host and port. AResultrecord holds the outcome of one check. - One check.
check()creates an unconnectedSocketand callsconnect()with a timeout. A successful connection means a program is listening on that port; the socket is closed straight away by try-with-resources. - Two kinds of failure. Port 6003 has no server, so the operating system refuses the connection (
ConnectException). The.invalidhost cannot be resolved at all (UnknownHostException). Both areIOExceptions, so onecatchhandles them. - Checking in parallel. Each check runs on its own virtual thread from
Executors.newVirtualThreadPerTaskExecutor(). Closing the executor waits for every task, so slow or timed-out services do not delay the others. See Java Virtual Threads for how this executor works. - Ordered report. The futures are read in the same order the services were listed, so the report is always in a stable order even though the checks finished at different times. The last line counts only the services that answered.
The same pattern works for real servers: replace the local stand-ins with your database, cache and API hosts. To check web services at the HTTP level instead of the TCP level, use the Java HttpClient and look at the status code.