Lesson · Networking
Networking Fundamentals: IP, TCP, DNS and the framing bug
14 min readFundamentals
Two processes exchanging bytes is one sentence; making it survive a network is the chapter. IP moves packets host to host with no promises, TCP turns that into an ordered byte stream, and your protocol has to supply the message boundaries TCP never had.
What actually moves between two processes
Your server is one process, the caller is another, and they usually run on different machines. IP addresses identify hosts and delivers packets between them best-effort: packets can be lost, reordered or duplicated on the way, and the network never tells either side which of those just happened.
TCP sits on top and repairs that picture. It numbers the bytes, retransmits what goes missing and delivers one ordered, reliable byte stream to the application. UDP stays closer to IP: every datagram keeps its boundary, and ordering, retries and connection state are simply absent.
HTTP, database protocols and every file transfer you have used live above this line. They all answered the same two questions first: how does a client find the server, and how do two sides agree where one message ends?
| Aspect | TCP | UDP |
|---|---|---|
| Model | Ordered byte stream | Independent datagrams |
| Reliability | Retransmits what is lost, reorders what arrives late | Best effort; loss is silent |
| Boundaries | None: your protocol defines them | One send is one datagram (within the size limit) |
| State | A connection both sides track | None beyond the socket |
| Typical fit | Request/response, file transfer, anything ordered | Discovery, metrics, DNS, real-time media |
TCP guarantees order and delivery, not message boundaries. Every framing bug below and every protocol design decision starts from that sentence.
DNS: a name has to become an address first
You configure db.internal:5432, but the network routes addresses, so the name is resolved before anything else can happen. The OS asks its configured resolver, the resolver answers from its cache or walks the DNS hierarchy, and the answer carries a TTL that says how long it may be reused.
The JVM keeps its own cache in front of that: networkaddress.cache.ttl (a security property) controls how long resolved addresses are reused, and networkaddress.cache.negative.ttl does the same for failures. Default lifetimes are implementation details, so a long-running JVM that must notice a DNS change tunes these deliberately.
- Lookups block.
InetAddress.getByNameperforms network I/O on the calling thread and has no timeout parameter of its own, so a slow resolver looks exactly like a hung application. - Failure is an exception. A name that cannot be resolved throws
UnknownHostException, from the connect call that needed the address rather than from a separate validation step. - The cache outlives the moment. A process can keep using an address that the DNS record no longer points to until its cache entry expires, which is why failover by DNS alone is not instant.
Resolution is network I/O. Treat a hostname lookup as a call that can block, fail and go stale, because it is one.
Sockets: an address, a port and a queue
A socket endpoint is an address plus a port: the address finds the machine, the port finds the process (or one listener inside it). The client connects from an ephemeral source port chosen by the OS, and the connection is identified by the whole pair of pairs: client address and port, server address and port.
On the server side, ServerSocket binds a port and starts listening; the kernel completes handshakes into a queue, and accept() pops one finished connection at a time. The queue is what the backlog parameter sizes, and it is why a connection can exist before your code has accepted it.
| Binding | Accepts traffic from | Typical use |
|---|---|---|
0.0.0.0:9099 | Every interface (the wildcard address) | Containers and public services |
127.0.0.1:9099 | The same machine only, over loopback | Dev databases, admin endpoints, anything that should never face the network |
| A specific interface address | That network card only | Multi-homed hosts that must separate traffic |
Listening on the wildcard when you meant loopback is a security decision you made by accident. Bind the narrowest address that works: 127.0.0.1 unless you have a reason to go wider.
The handshake, and the state you never see
A TCP connection begins with SYN, SYN-ACK, ACK: three messages, none of them your code. Both kernels then hold state for the connection (sequence numbers, windows, retransmission timers), and the client's ACK can carry its first payload, so data can reach the server after roughly one and a half round trips from the moment connect started.
Closing is another exchange, after which the side that closed first sits in TIME_WAIT for twice the maximum segment lifetime. That grace period exists so delayed duplicates from the finished connection cannot be mistaken for the next connection that reuses the same address and port pair.
An established connection can also be dead without both sides knowing: a crashed peer, an expired NAT entry, a pulled cable. Nothing raises an exception on its own; your side notices on a write (when retransmissions finally give up) or when a read times out.
- Client sends SYN with its initial sequence number and an ephemeral source port.
- Server answers SYN-ACK, acknowledging that number and sending its own.
- Client sends ACK, and the connection is established; its first payload can travel in that same message.
- Either side ends by sending FIN; the peer acknowledges, and the active closer waits in TIME_WAIT before the address and port pair is reusable.
- A silent peer is discovered by a write that eventually fails or a read that hits its timeout, never by the kernel volunteering the news.
A connection is a state machine in the kernel, not a flag in your object. Your code holds a handle to it; the two kernels hold the truth.
The framing bug: TCP has no message boundaries
You wrote two messages, so you expect to read two messages. TCP never promised that: it delivers a byte stream, and a read() returns as many bytes as happen to be available, which can be a fragment of one message, exactly one message, or several messages glued together.
The naive parser assumes the third case never happens: it treats every read as one message and moves on. It works on loopback where messages travel one at a time, until two small writes coalesce into one segment (or one large write splits into two) and the parser silently drops, truncates or corrupts data with no exception anywhere.
write() is not a send either: it hands bytes to a buffer, and the kernel decides when and in what shape they travel. Reliability does not rescue you here, because nothing was lost. Your parser simply misread what arrived.
String line = in.readLine(); handle(line); // one read, one message... until two messages arrive in one read: the second is lost
- Length-prefixed frames: a fixed-size header (commonly 4 bytes) states the payload length, so the reader knows exactly how many bytes one frame occupies.
- Delimiters: a byte sequence that must not appear in the payload (a newline, a NUL byte) ends each message. Simple, and it needs escaping for payloads that may contain it.
- Fixed-size records: every frame is exactly N bytes. Predictable and cache-friendly, and wasteful when messages vary in size.
- The read loop is not optional: whatever the format, the receiver accumulates bytes until a complete frame is available, then parses and repeats, keeping any leftover for the next round.
Boundaries are a protocol decision, not a transport feature. Pick a framing rule before you write the first write(), and make the receiver loop until it has a whole frame.
One connection · two messages
Two messages are queued in the client: LOGIN|ana, then MSG|hi. The client knows a name, db.internal:9099, and a name is not routable, so resolving it comes first.
Serving many connections: three shapes
A connection is state you hold for as long as the client stays, and who waits for it defines a server's architecture. Three answers dominate, and each one moves the cost of waiting somewhere different.
- Thread per connection: each client gets a thread that blocks on read and write. Trivial to write, and it runs out of room in the low thousands of threads, because every blocked thread keeps a stack and every wakeup costs a scheduler decision.
- Event loop with a selector: one thread watches many sockets through
java.nioselectors and handles whichever are ready. It scales to very large connection counts and forces callbacks or state machines, because blocking on one connection would stall all the others. - Virtual threads (Java 21): the same blocking code as thread per connection, but a blocked virtual thread does not hold its carrier thread, so the simple style scales to huge connection counts.
You do not have to choose today: this lesson is the map. The concurrency part of the course covers selectors and virtual threads in depth.
Reading these bugs from the symptom
Network bugs rarely announce themselves as network bugs. These are the shapes you will actually meet, with the mechanism behind each one.
- A parser that drops data in production but never on your machine: two small messages arrived in one read, or a large one arrived in fragments. The fix is framing plus an accumulating read loop, never a longer sleep.
- The server never sees data the client already wrote: the bytes are sitting in a buffer (the socket's, or a
PrintWriterthat was never flushed).write()only queues. - A connection that looks alive hours after the peer died: a dead peer is silence, and silence raises nothing. Set a read timeout and, for long-lived connections, an application-level heartbeat.
- A connect that hangs instead of failing: a slow DNS lookup or a dropped SYN that draws no response. Both end only when a timeout ends them, and
connect()without a timeout waits for the OS, which on common defaults takes minutes.
Every one of those failures is ordinary application logic meeting a transport that made no promises. The transport is not broken; the assumption was.
write() is not a send, read() is not a message
write() hands bytes to the kernel; read() hands back whatever has arrived, in whatever sizes the network produced. Everything else in this lesson follows from that: buffers exist at both ends, boundaries come from your framing rule, and only an explicit timeout turns silence into an error. If your parser depends on read sizes, it is broken in a way that local testing cannot reveal.
Interview angles
TCP is reliable. Why does my parser still see half a message?+
Reliable means the bytes arrive in order and without gaps, not that they arrive in the sizes you wrote. A read() returns whatever is in the receive buffer, from one byte to several messages.
The kernel reassembles the stream, and your application consumes it in chunks whose sizes depend on timing, segment sizes and buffer space. So the protocol must define boundaries itself (length prefixes, delimiters or fixed-size records) and the receiver must loop until a whole frame is buffered.
Common misconception: The common belief is that one write() on one side produces exactly one read() on the other. It is only usually true, and loopback testing is where it is most true, which is why the bug ships.
What happens between connect() and accept()?+
The kernel completes the three-way handshake and parks the connection in the listening socket's backlog queue. accept() then returns one connected socket at a time.
SYN, SYN-ACK, ACK: roughly one and a half round trips before the first application data can arrive, and both sides keep per-connection state from then on. The backlog lets connections complete while your thread is busy, which is why doing real work inside the accept loop makes a queue look like an outage.
Follow-up: What is TIME_WAIT for?
Why does an InetAddress lookup block?+
Resolving a name is a network conversation with a resolver, so the call performs I/O and has no timeout parameter of its own. The JVM caches results on top of the OS cache, with lifetimes set by networkaddress.cache.ttl.
Failures arrive as UnknownHostException from inside the connect call, a slow lookup looks like a hang, and a long-running JVM can keep using a stale address until the cache entry expires, which matters when a service moves behind its DNS name.
When is UDP the right choice?+
When a late datagram is worse than a lost one and you can tolerate loss: discovery, metrics, DNS itself, real-time media. You keep the message boundary UDP gives you and accept that ordering, retries and connection state become your problem if you need them.
In theory an IPv4 datagram payload can reach about 65,507 bytes. In practice anything beyond the path MTU is fragmented at the IP layer, and losing one fragment loses the whole datagram, so real protocols keep them small.
Thread per connection, a selector event loop, or virtual threads?+
Thread per connection is the simplest blocking code and stops scaling around thousands of threads. A selector event loop scales to huge connection counts and demands non-blocking state machines. Virtual threads (Java 21) keep the blocking style and scale, because a blocked virtual thread does not hold its carrier thread.