Networking Basics

IP addresses, packets, ports, TCP vs UDP and the layers that move data between machines.

What is it?

Every distributed system is just computers sending bytes to each other. To do that, the network needs answers to three questions: which machine (an IP address), which program on that machine (a port), and how carefully to deliver the data (a transport protocol such as TCP or UDP).

Data doesn't travel as one big blob. It is cut into small packets (typically up to about 1,500 bytes on Ethernet), each carrying the source and destination address. Routers forward each packet hop by hop toward its destination, and the receiver puts them back together.

- TCP gives you a reliable, ordered stream of bytes. Lost packets are resent, duplicates are dropped, and the sender slows down if the network is congested. HTTP/1.1, HTTP/2, SSH and database protocols use it. - UDP just sends individual datagrams with no guarantee of delivery or order. It's faster to start and has less overhead, so it's used for DNS lookups, video calls, games and QUIC (the transport under HTTP/3).

Explain like I'm 10

An IP address is a building's street address, the port is the apartment number, TCP is registered mail (signed for, resent if lost, delivered in order), and UDP is dropping postcards in a mailbox: cheap and fast, but some may never arrive.

Examples

Inspecting connections from a shell

# Which IP does this hostname resolve to?
dig +short example.com

# Is anything listening on port 443 there? (TCP handshake test)
nc -vz example.com 443

# Which hops do packets take to get there?
traceroute example.com

# Which ports is my own machine listening on?
lsof -iTCP -sTCP:LISTEN -n -P

TCP vs UDP in Node.js

import net from "node:net";
import dgram from "node:dgram";

// TCP: open a connection first, then stream bytes in order.
const socket = net.connect(5000, "10.0.0.5", () => {
  socket.write("hello over TCP");
});

// UDP: no connection, just fire a datagram at an address.
const udp = dgram.createSocket("udp4");
udp.send("hello over UDP", 5001, "10.0.0.5", () => udp.close());

The TCP client must complete a handshake before sending anything. The UDP client sends immediately and never learns whether the datagram arrived.

How it works

Networking is organised in layers. Each layer solves one problem and relies on the one below it. The OSI model has seven layers, but the practical TCP/IP model has four:

1. Link (Ethernet, Wi-Fi): moves frames between machines on the same local network using MAC addresses. 2. Internet (IP): gives every host an address and routes packets across networks. IPv4 addresses are 32 bits (about 4.3 billion, e.g. 203.0.113.7); IPv6 addresses are 128 bits (e.g. 2001:db8::1). IP is "best effort": packets can be lost, duplicated or reordered. 3. Transport (TCP, UDP): adds ports (16-bit numbers, 0–65535) so many programs can share one IP. TCP adds reliability, ordering and congestion control on top of IP; UDP adds almost nothing. 4. Application (HTTP, DNS, SMTP, gRPC): the protocol your code speaks.

A connection is identified by the 4-tuple (source IP, source port, destination IP, destination port). Servers listen on well-known ports (80 HTTP, 443 HTTPS, 22 SSH, 53 DNS, 5432 Postgres); clients get a temporary ephemeral port from the OS.

The TCP three-way handshake sets up a connection before any data flows: the client sends SYN, the server replies SYN-ACK, the client answers ACK. That costs one full round trip, and TLS on top adds one more (TLS 1.3) or two (TLS 1.2). This is why reusing connections (keep-alive, connection pools) matters so much for latency. Closing uses FIN/ACK, and the side that closes first sits in TIME_WAIT for a while so stray packets from the old connection can't confuse a new one.

Client                               Server (port 443)
  │ ── SYN (seq=x) ──────────────────▶ │
  │ ◀── SYN-ACK (seq=y, ack=x+1) ───── │   1 round trip
  │ ── ACK (ack=y+1) ────────────────▶ │
  │ ── data (e.g. TLS ClientHello) ──▶ │   connection is open

Layers on the way out:
  HTTP request        (application)
   └ TCP segment      (transport: ports, sequence numbers)
      └ IP packet     (internet: source/destination IP)
         └ Ethernet   (link: MAC addresses)

Why does it exist?

The underlying network is unreliable: links drop packets, routers queue and reorder them, and paths change. Layering lets each problem be solved once. IP handles addressing and routing, TCP turns lossy packets into a reliable stream, and applications can ignore all of that and just read and write bytes.

When to use it

You use this knowledge whenever you reason about latency (how many round trips a request needs), choose a protocol (TCP for correctness, UDP when late data is useless), configure firewalls and security groups (which ports are open), debug "connection refused" vs "connection timed out", or size connection pools.

When not to use it

Don't build your own reliability layer on raw UDP unless you really need it; QUIC or TCP already solve retransmission and congestion control correctly. And don't drop down to raw sockets when an application protocol like HTTP or gRPC already fits; you'd be re-inventing framing, errors and timeouts.

Common mistakes

  • Assuming TCP guarantees the other application processed your message. It only guarantees the bytes reached the remote kernel's buffer; you still need application-level acknowledgements.

  • Treating TCP as message-based. It is a byte stream, so one write can arrive as several reads (or several writes as one), and you need your own framing (length prefixes or delimiters).

  • Opening a new connection per request and paying the TCP + TLS handshake every time instead of reusing connections.

  • Confusing 'connection refused' (host reachable, nothing listening on the port) with a timeout (packets dropped, often by a firewall or a dead host).

  • Forgetting that private ranges (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16) are not reachable from the internet without NAT or a load balancer.

Practice exercises

  1. Easy:

    Run nc -vz against port 443 and port 81 of a public website. Explain the difference in the results.

  2. Medium:

    A client in Mumbai talks to a server in Virginia with a 200 ms round-trip time. How long before the first byte of an HTTPS response arrives on a fresh connection using TLS 1.3, ignoring server processing and DNS? What if the connection is reused?

  3. Hard:

    Design a framing format for sending variable-length JSON messages over a raw TCP socket, and explain how the receiver handles a message split across two reads.

Interview questions

What's the difference between TCP and UDP?

TCP is connection-oriented and gives a reliable, ordered byte stream with retransmission, flow control and congestion control. UDP is connectionless and sends independent datagrams with no delivery or ordering guarantees, but with less overhead and no handshake.

What is a port, and why do we need one if we have an IP address?

An IP address identifies a host; a port (0–65535) identifies a specific program on it. Ports let many services share one IP, and the 4-tuple of IPs and ports identifies each connection.

Walk through the TCP three-way handshake.

Client sends SYN with its initial sequence number. Server replies SYN-ACK with its own sequence number and acknowledges the client's. Client sends ACK. Both sides now agree on sequence numbers and the connection is open; it costs one round trip.

Why do video calls and games often use UDP?

For real-time media, a late packet is useless. TCP would stall the whole stream waiting to resend a lost packet (head-of-line blocking). With UDP the app skips or conceals the loss and keeps going.

What are the layers of the TCP/IP model, and what does each do?

Link (frames on a local network), Internet (IP addressing and routing), Transport (ports, plus reliability for TCP), Application (HTTP, DNS, etc.). Each layer wraps the data from the layer above in its own header.

What is the difference between 'connection refused' and 'connection timed out'?

Refused means the host answered with a TCP RST because nothing is listening on that port. Timed out means no answer at all: the host is down, unreachable, or a firewall silently drops the packets.

Why is connection reuse so important for latency?

A new HTTPS connection costs a TCP round trip plus one or two TLS round trips before any data moves. On a 100 ms RTT link that's 200–300 ms of pure setup. Keep-alive and pooling pay it once.

What is head-of-line blocking at the TCP level, and how does HTTP/3 address it?

TCP delivers bytes strictly in order, so one lost packet stalls all data behind it, even for unrelated HTTP/2 streams sharing the connection. HTTP/3 runs over QUIC (on UDP), which handles loss per stream so other streams keep flowing.

What is TIME_WAIT, and when does it become a problem?

After actively closing a connection, a socket stays in TIME_WAIT (typically 2×MSL, often 60 s on Linux) so delayed packets can't corrupt a new connection with the same 4-tuple. A client opening many short-lived connections to one destination can exhaust ephemeral ports; the fix is connection reuse.

A load balancer handles 100,000 concurrent connections to one backend IP and port. What limit might it hit?

Each outbound connection needs a unique 4-tuple, and with fixed source IP, destination IP and port, only the source port varies, giving roughly 28,000–64,000 usable ephemeral ports. Fixes: multiple source IPs, more backend IPs/ports, or connection pooling/multiplexing.