Java Sockets: Connecting to a Server, Timeouts and InetAddress
Connect to network services from Java: ports and TCP connections, experimenting with telnet and netcat, Socket with input and output streams, connect and read timeouts, ConnectException, InetAddress and InetSocketAddress, address literals with ofLiteral, and a glimpse of UDP.
kvi5hnuCode Sprout team member10 min readOn this page
Part 4 of the course is about networking: talking to other programs over TCP/IP, first with plain sockets, then with HTTP. This article starts on the client side. It shows how to connect to a server, exchange data, and avoid waiting forever when something goes wrong.
Ports and connections
A computer on a network is reached through an IP address, such as 129.6.15.28 (IPv4, 4 bytes) or 2001:db8::1 (IPv6, 16 bytes). Many programs on the same host can offer services, so each service listens on a numbered port, from 0 to 65535. A port isn't a physical thing. It's a number that the operating system uses to deliver incoming connections to the right program. Well-known services have conventional ports: 13 for the old "daytime" service, 25 for mail (SMTP), 80 for HTTP, 443 for HTTPS. On Linux, listening on a port below 1024 requires administrator rights (or a capability such as CAP_NET_BIND_SERVICE). macOS (since 10.14) and Windows allow ordinary programs to use them.
A TCP connection is identified by both endpoints: the server's address and port, and the client's address and port. The client's port is a temporary ("ephemeral") one that the operating system picks. That's how a server can talk to thousands of clients on the same port.

TCP delivers a reliable, ordered stream of bytes in both directions. Above it, each service defines its own protocol: who speaks first, what the messages look like, and when the connection ends.
Experimenting by hand
Before writing code, it's instructive to talk to a server manually. The classic tool is telnet host port, which connects and then copies your keystrokes to the server and its replies to the screen. Telnet is no longer installed by default on macOS or Windows. nc (netcat), ncat or curl serve the same purpose. Try:
nc time-a.nist.gov 13
The NIST time server answers with a line containing the current date and time and closes the connection. Or speak HTTP to a web server:
nc example.com 80
GET / HTTP/1.1
Host: example.com
After the blank line, the server sends a status line, headers, a blank line and the HTML of the page. That's exactly what a browser does, minus the rendering. The Host header tells a server that hosts many sites at one address which one you want. Most sites today only serve HTTPS on port 443, where the bytes are encrypted, so you need openssl s_client -connect example.com:443 (or curl -v) to see anything.
Connecting from Java
The java.net.Socket class gives a TCP connection the same interface as a file: an input stream and an output stream.
try (var s = new Socket("time-a.nist.gov", 13);
var in = new Scanner(s.getInputStream(), StandardCharsets.UTF_8)) {
while (in.hasNextLine())
System.out.println(in.nextLine());
}
The constructor looks up the host name, connects, and throws an IOException if anything fails: UnknownHostException if the name can't be resolved, ConnectException if nothing listens on the port ("Connection refused"), or other subclasses for unreachable networks. getInputStream and getOutputStream return byte streams. Wrap them in readers and writers with an explicit charset, as article 20 described. Closing the socket, or either stream, closes the connection.
This program works because the daytime protocol is trivial: the server talks, then hangs up, and hasNextLine returns false at the end of the stream. In most protocols the client sends a request first and must know when the response is complete, because the server may keep the connection open. HTTP, for example, announces the body length in a Content-Length header. And when you write requests through a PrintWriter or BufferedWriter, flush it, or the bytes may sit in a buffer while both sides wait for each other.
Timeouts
By default, socket operations can block for a very long time:
- Connecting to a host that doesn't answer (a firewall that silently drops packets) blocks until the operating system gives up, which can take minutes.
- Reading blocks until data arrives, forever if the server never sends anything.
Handle both explicitly. Create an unconnected socket and connect with a timeout in milliseconds, then set a read timeout:
var s = new Socket();
s.connect(new InetSocketAddress(host, port), 5_000); // connect timeout
s.setSoTimeout(10_000); // read timeout
When a read exceeds the timeout, it throws a SocketTimeoutException (an InterruptedIOException). The socket stays open, so you can retry or give up. There's no timeout for writes: a write blocks only when the operating system's send buffer is full, because the peer isn't reading. Article 50 shows how to make socket operations interruptible.
Internet addresses
You rarely need to deal with addresses directly, since Socket accepts host names. When you do, java.net.InetAddress represents an IP address, with the subclasses Inet4Address and Inet6Address.
InetAddress address = InetAddress.getByName("time-a.nist.gov"); // DNS lookup
InetAddress[] all = InetAddress.getAllByName("example.com"); // all addresses of a host
byte[] bytes = address.getAddress(); // 4 or 16 bytes
String text = address.getHostAddress(); // "129.6.15.28"
Busy hosts often have several addresses for load balancing, and getAllByName returns all of them. Note that getAddress returns signed Java bytes, so 129 shows up as -127. Use Byte.toUnsignedInt to print the usual form.
Some other factory methods and checks:
InetAddress.getLoopbackAddress()returns the loopback address (127.0.0.1or::1), which only reaches your own machine. Nobody else can connect to you through it.InetAddress.getLocalHost()returns an address of your machine as other hosts see it, if the configuration allows.InetAddress.getByAddress(bytes)andgetByAddress(name, bytes)build an address without any lookup.InetAddress.ofLiteral("192.168.1.1")(Java 22), together withInet4Address.ofLiteralandInet6Address.ofLiteral, parses a numeric address and throwsIllegalArgumentExceptionfor anything else. UnlikegetByName, it never performs a DNS lookup by accident.isLoopbackAddress(),isSiteLocalAddress()(private ranges such as192.168.x.x),isLinkLocalAddress(),isMulticastAddress()andisAnyLocalAddress()classify addresses.
InetSocketAddress combines an address (or an unresolved host name) with a port. It's what connect and bind take. InetSocketAddress.createUnresolved(host, port) skips the lookup, which is useful when a proxy will resolve the name. Name resolution normally uses the operating system's resolver and caches results according to the security properties networkaddress.cache.ttl and networkaddress.cache.negative.ttl. Since Java 18 (JEP 418), you can plug in your own resolver through the InetAddressResolverProvider service interface, for example to test code without real DNS.
The program
To stay independent of outside servers, the demo starts its own tiny servers on the loopback interface, each on a free port picked by passing port 0. (Article 49 explains server sockets.) It reads a line from a "time" server, sends an HTTP-style request to a second server and prints the raw response, triggers a read timeout against a server that never answers, and gets "Connection refused" from a port with no listener. Then it works with addresses without any DNS lookups, and finally exchanges one UDP datagram.
import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
public class Solution {
/** A tiny "time of day"-style server: sends one line and hangs up. Port 0 picks a free port. */
static ServerSocket startGreetingServer() throws IOException {
var server = new ServerSocket(0, 50, InetAddress.getLoopbackAddress());
Thread.ofVirtual().start(() -> {
try (server; Socket client = server.accept();
var out = new PrintWriter(new OutputStreamWriter(client.getOutputStream(), StandardCharsets.UTF_8), true)) {
out.println("2026-11-14 12:00:00 UTC (loopback clock)");
} catch (IOException e) {
System.out.println("server: " + e.getMessage());
}
});
return server;
}
/** Answers one HTTP-like request, echoing the request line and the Host header. */
static ServerSocket startHttpLikeServer() throws IOException {
var server = new ServerSocket(0, 50, InetAddress.getLoopbackAddress());
Thread.ofVirtual().start(() -> {
try (server; Socket client = server.accept();
var in = new BufferedReader(new InputStreamReader(client.getInputStream(), StandardCharsets.US_ASCII));
var out = new PrintWriter(new OutputStreamWriter(client.getOutputStream(), StandardCharsets.US_ASCII))) {
String requestLine = in.readLine();
String host = "?";
for (String h = in.readLine(); h != null && !h.isEmpty(); h = in.readLine())
if (h.regionMatches(true, 0, "Host:", 0, 5)) host = h.substring(5).strip();
String body = "<p>You asked for " + requestLine.split(" ")[1] + " on " + host + "</p>";
out.print("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: " + body.length()
+ "\r\nConnection: close\r\n\r\n" + body);
out.flush();
} catch (IOException e) {
System.out.println("server: " + e.getMessage());
}
});
return server;
}
public static void main(String[] args) throws Exception {
System.out.println("--- reading from a server ---");
ServerSocket greeting = startGreetingServer();
try (var s = new Socket(InetAddress.getLoopbackAddress(), greeting.getLocalPort());
var in = new Scanner(s.getInputStream(), StandardCharsets.UTF_8)) {
System.out.println("connected: " + s.isConnected() + ", remote is loopback: "
+ s.getInetAddress().isLoopbackAddress() + ", local port != remote port: " + (s.getLocalPort() != s.getPort()));
while (in.hasNextLine()) System.out.println("received: " + in.nextLine());
}
System.out.println("--- a request and a response, like telnet host 80 ---");
ServerSocket http = startHttpLikeServer();
try (var s = new Socket()) {
s.connect(new InetSocketAddress(InetAddress.getLoopbackAddress(), http.getLocalPort()), 2000);
s.setSoTimeout(5000);
var out = new PrintWriter(new OutputStreamWriter(s.getOutputStream(), StandardCharsets.US_ASCII));
out.print("GET /index.html HTTP/1.1\r\nHost: example.com\r\n\r\n");
out.flush();
var in = new BufferedReader(new InputStreamReader(s.getInputStream(), StandardCharsets.US_ASCII));
in.lines().forEach(line -> System.out.println("< " + line));
}
System.out.println("--- read timeout ---");
try (var silent = new ServerSocket(0, 50, InetAddress.getLoopbackAddress());
var s = new Socket(InetAddress.getLoopbackAddress(), silent.getLocalPort())) {
s.setSoTimeout(200);
try {
int b = s.getInputStream().read(); // the server never sends anything
System.out.println("read " + b);
} catch (SocketTimeoutException e) {
System.out.println(e.getClass().getSimpleName() + ": " + e.getMessage() + "; socket still open: " + !s.isClosed());
}
}
System.out.println("--- nobody listening ---");
int closedPort;
try (var temp = new ServerSocket(0, 50, InetAddress.getLoopbackAddress())) {
closedPort = temp.getLocalPort();
}
try (var s = new Socket()) {
s.connect(new InetSocketAddress(InetAddress.getLoopbackAddress(), closedPort), 2000);
} catch (ConnectException e) {
System.out.println("ConnectException: " + e.getMessage());
}
System.out.println("--- Internet addresses (no DNS needed) ---");
InetAddress v4 = InetAddress.getByName("129.6.15.28"); // a literal: no lookup
System.out.println(v4 + " bytes " + Arrays.toString(v4.getAddress()) + " -> unsigned "
+ Arrays.toString(toUnsigned(v4.getAddress())) + ", " + v4.getClass().getSimpleName());
InetAddress v6 = InetAddress.ofLiteral("2001:db8::1"); // Java 22
System.out.println(v6.getHostAddress() + ", " + v6.getAddress().length + " bytes, " + v6.getClass().getSimpleName());
System.out.println("loopback: " + InetAddress.getLoopbackAddress().getHostAddress()
+ ", ::1 is loopback: " + InetAddress.ofLiteral("::1").isLoopbackAddress());
InetAddress built = InetAddress.getByAddress("printer", new byte[] {(byte) 192, (byte) 168, 1, 20});
System.out.println("getByAddress: " + built + ", site-local: " + built.isSiteLocalAddress());
try {
InetAddress.ofLiteral("not-an-address");
} catch (IllegalArgumentException e) {
System.out.println("ofLiteral rejects host names: " + e.getMessage());
}
var socketAddress = new InetSocketAddress("10.0.0.7", 8080);
System.out.println("InetSocketAddress: " + socketAddress + ", unresolved: " + socketAddress.isUnresolved()
+ "; createUnresolved: " + InetSocketAddress.createUnresolved("db.internal", 5432).isUnresolved());
System.out.println("--- UDP on loopback ---");
try (var receiver = new DatagramSocket(0, InetAddress.getLoopbackAddress());
var sender = new DatagramSocket()) {
byte[] data = "ping".getBytes(StandardCharsets.UTF_8);
sender.send(new DatagramPacket(data, data.length, InetAddress.getLoopbackAddress(), receiver.getLocalPort()));
var packet = new DatagramPacket(new byte[512], 512);
receiver.setSoTimeout(2000);
receiver.receive(packet);
System.out.println("datagram: " + new String(packet.getData(), 0, packet.getLength(), StandardCharsets.UTF_8));
}
}
static int[] toUnsigned(byte[] bytes) {
int[] result = new int[bytes.length];
for (int i = 0; i < bytes.length; i++) result[i] = Byte.toUnsignedInt(bytes[i]);
return result;
}
}
--- reading from a server ---
connected: true, remote is loopback: true, local port != remote port: true
received: 2026-11-14 12:00:00 UTC (loopback clock)
--- a request and a response, like telnet host 80 ---
< HTTP/1.1 200 OK
< Content-Type: text/html
< Content-Length: 47
< Connection: close
<
< <p>You asked for /index.html on example.com</p>
--- read timeout ---
SocketTimeoutException: Read timed out; socket still open: true
--- nobody listening ---
ConnectException: Connection refused (connect failed)
--- Internet addresses (no DNS needed) ---
/129.6.15.28 bytes [-127, 6, 15, 28] -> unsigned [129, 6, 15, 28], Inet4Address
2001:db8:0:0:0:0:0:1, 16 bytes, Inet6Address
loopback: 127.0.0.1, ::1 is loopback: true
getByAddress: printer/192.168.1.20, site-local: true
ofLiteral rejects host names: Invalid IP address literal: not-an-address
InetSocketAddress: /10.0.0.7:8080, unresolved: false; createUnresolved: true
--- UDP on loopback ---
datagram: ping
Common questions
What's the difference between "Connection refused" and a connect timeout? "Refused" means the host answered and said that nothing listens on that port: fast and definite. A timeout means no answer at all, typically because a firewall silently drops packets, the host is down, or the address is wrong. Without a connect timeout, that case can hang for a minute or more.
How do I know when the server has finished sending?
The protocol must say so. The options are: the server closes the connection (read returns -1, readLine returns null), a length is announced first (like HTTP's Content-Length), or a delimiter marks the end (such as a blank line). available() is not an answer; it only reports what has already arrived.
Should I use raw sockets for HTTP? No. Use the HTTP client (article 53), which handles HTTPS, redirects, chunked encoding, compression, HTTP/2 and connection reuse. Raw sockets are for your own protocols, or ones without a library.
Why does my program connect to an IPv6 address when I expected IPv4?
Host names often resolve to both, and the order depends on the system. -Djava.net.preferIPv4Stack=true disables IPv6 in the JVM, and -Djava.net.preferIPv6Addresses=true (or system) changes the preference. Usually, just let the system choose.
Why does DNS change not show up in my long-running program?
Successful lookups are cached for 30 seconds by default (networkaddress.cache.ttl). Failed lookups are cached for 10 seconds. Set these security properties in conf/security/java.security or with Security.setProperty early in the program.
Is Socket thread-safe?
You can read on one thread and write on another at the same time, which is common for full-duplex protocols. Don't let two threads write to the same stream concurrently, or their bytes interleave.
API reference
| API | Purpose |
|---|---|
new Socket(host, port), new Socket(InetAddress, port) | connect immediately |
new Socket() + connect(SocketAddress, timeoutMillis) | connect with a timeout |
Socket.getInputStream(), getOutputStream() | the byte streams of the connection |
Socket.setSoTimeout(millis) | read timeout; SocketTimeoutException when exceeded |
Socket.isConnected(), isClosed(), getPort(), getLocalPort(), getInetAddress() | state and endpoints |
InetAddress.getByName(host), getAllByName(host) | resolve names (or parse literals) |
InetAddress.ofLiteral(text) | parse a numeric address only (Java 22) |
InetAddress.getByAddress([name,] bytes) | address from raw bytes |
InetAddress.getLoopbackAddress(), getLocalHost() | the loopback address, the local host |
InetAddress.getAddress(), getHostAddress(), getHostName() | bytes, text form, name |
InetSocketAddress(host, port), createUnresolved(host, port) | socket addresses |
DatagramSocket, DatagramPacket | UDP |
Summary
- A TCP connection links an address and port on each side. Servers listen on known ports, and clients get temporary ones.
- Tools like
nc,curlandopenssl s_clientlet you speak a protocol by hand before you code it. Socketconnects to a host and port and offers an input and an output stream. Wrap them with explicit charsets, and flush buffered writers.- Always use timeouts:
connect(address, timeout)for connecting andsetSoTimeoutfor reading. InetAddressrepresents IPv4 and IPv6 addresses.ofLiteralparses numeric addresses without DNS, andInetSocketAddressadds the port.
Practice Questions
Why can a single server process on port 80 serve many clients at once without the connections getting mixed up?
A TCP connection is identified by four values: client address, client port, server address and server port. Each client connection has a different client address or temporary client port, so the operating system can tell them apart, even though they all use server port 80.
A client calls new Socket(host, port) and the program hangs for two minutes before failing. What happened, and how do you prevent it?
The host probably drops connection attempts silently, for example because of a firewall, so the connect waits until the operating system's own timeout. Create the socket unconnected and call s.connect(new InetSocketAddress(host, port), timeoutMillis). Also set setSoTimeout so that a later read can't hang either.
What's the difference between a ConnectException and a SocketTimeoutException?
A ConnectException ("Connection refused") means the host answered but nothing listens on that port, and the failure is immediate. A SocketTimeoutException means an operation, either a connect with a timeout or a read with setSoTimeout, didn't complete in time, typically because the other side doesn't respond.
Why does InetAddress.getByName("129.6.15.28").getAddress()[0] return -127?
getAddress returns a byte[], and Java bytes are signed, ranging from -128 to 127. The unsigned value 129 is stored as the bit pattern 10000001, which is -127 as a signed byte. Use Byte.toUnsignedInt to get 129.
When would you prefer InetAddress.ofLiteral over InetAddress.getByName?
When the input is supposed to be a numeric IP address, such as a value from a configuration file. ofLiteral parses it and rejects anything else, while getByName would silently perform a DNS lookup for a host name, which can be slow, can fail, or can be steered by whoever controls DNS.
Previous: XSL Transformations in Java: Stylesheets and the Transformer API
Next: Java Server Sockets: Serving Multiple Clients with Threads and Virtual Threads
Related reading
- XSL Transformations in Java: Stylesheets and the Transformer API
- Generating XML in Java: Building DOM Trees and Writing with Transformer, LSSerializer and StAX
- Streaming XML Parsers in Java: SAX and StAX
- XML Namespaces: Prefixes, Default Namespaces and Namespace-Aware Parsing
- Querying XML with XPath: Expressions and the XPath API

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.