Try Embedded

TCP/IP fundamentals

Layers, the handshake, flow and congestion control, and lwIP.

The layers

The TCP/IP model has four layers. Each adds its own header in front of the data from the layer above (encapsulation), and the receiver strips them in reverse.

LayerJobExamplesAddressing
ApplicationWhat the data meansHTTP, MQTT, CoAP, DNS, NTP, DHCP—
TransportEnd-to-end delivery between programsTCP, UDPPort numbers
Internet (network)Routing packets across networksIPv4, IPv6, ICMPIP addresses
LinkDelivery on one physical networkEthernet, Wi-Fi (802.11), 802.15.4, PPP; ARPMAC addresses

An MQTT message over Ethernet is: Ethernet header (14 bytes) + IPv4 header (20) + TCP header (20 or more) + MQTT, plus the TLS record if encrypted, plus the Ethernet checksum.

IP

IPv4 addresses are 32 bits (192.168.1.20), with a subnet mask (/24 = 255.255.255.0) saying which part identifies the network. A host sends directly to addresses on its own subnet (after finding their MAC address with ARP), and everything else to its default gateway (the router).

#include <stdio.h>
#include <stdint.h>

static uint32_t ip(int a, int b, int c, int d) { return ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8) | (uint32_t)d; }
static void show(const char *label, uint32_t v) {
  printf("%-10s %u.%u.%u.%u\n", label, v >> 24, (v >> 16) & 255, (v >> 8) & 255, v & 255);
}

int main(void) {
  uint32_t me = ip(192, 168, 1, 20), mask = 0xFFFFFF00u;   /* /24 */
  uint32_t targets[2] = { ip(192, 168, 1, 77), ip(8, 8, 8, 8) };
  show("network", me & mask);
  show("broadcast", (me & mask) | ~mask);
  for (int i = 0; i < 2; i++) {
    show("target", targets[i]);
    printf("           -> %s\n", (targets[i] & mask) == (me & mask) ? "same subnet: ARP for its MAC, send directly"
                                                              : "different network: send to the default gateway");
  }
  return 0;
}

IP is best effort: packets can be lost, duplicated, reordered or fragmented. ICMP carries errors and diagnostics (ping). Devices usually get their address, mask, gateway and DNS server from DHCP.

IPv6 uses 128-bit addresses, has no ARP (Neighbour Discovery instead) and no broadcast, and is native to Thread and many cellular IoT networks.

TCP

TCP turns unreliable packets into a reliable, ordered byte stream.

The three-way handshake

client                      server
  | -- SYN (seq=x) ----------> |
  | <- SYN+ACK (seq=y, ack=x+1)|
  | -- ACK (ack=y+1) --------> |   connection established

Each side picks an initial sequence number; every byte is then numbered, so the receiver can reorder and detect gaps. Closing uses FIN from each side (four segments), and the side that closes first waits in TIME_WAIT (2 × maximum segment lifetime) so late packets cannot confuse a new connection on the same ports.

Reliability

The receiver acknowledges the highest in-order byte received. The sender keeps unacknowledged data and retransmits it if no ACK arrives within the retransmission timeout (RTO), which adapts to the measured round-trip time. Three duplicate ACKs trigger a faster retransmission.

Flow control

The receiver advertises a window: how many more bytes it can buffer. The sender never has more than that unacknowledged. A small embedded device with a 2 KB receive buffer advertises a small window, which caps throughput at roughly window / round-trip time:

2048 bytes / 0.1 s RTT ≈ 20 KB/s, however fast the link

Congestion control

Separately from the receiver's window, the sender limits itself to avoid overloading the network: slow start doubles the congestion window each round trip, then congestion avoidance grows it linearly; packet loss halves it. The effective window is the smaller of the two.

Other pieces you will meet

ProtocolJob
DHCPObtain an IP address and settings automatically
DNSTurn names into addresses (UDP port 53)
ARPFind the MAC address for an IPv4 address on the local network
NTP / SNTPSet the clock (needed for TLS certificate validation)
ICMPErrors and ping
mDNS / DNS-SDFind devices on a local network without a DNS server (device.local)
NATA router translating private addresses to one public address; why devices behind it cannot be reached from outside without an outbound connection

TCP/IP on a microcontroller

lwIP is the most common stack: small (around 40 KB flash, configurable RAM), with three APIs: the raw callback API (no RTOS needed, most efficient), the netconn API, and BSD-style sockets (needs an RTOS). Alternatives: FreeRTOS+TCP, Zephyr's native stack, NetX Duo, and stacks inside Wi-Fi or cellular modules (accessed with AT commands, offloading TCP/IP entirely).

Tuning that matters:

  • Buffer pools (pbufs) and memory: too few, and packets are dropped under load.
  • TCP window and MSS: larger windows give throughput at a RAM cost; MSS is typically 1460 bytes on Ethernet.
  • Number of sockets and connections: each costs RAM.
  • Checksum offload: many Ethernet MACs compute IP/TCP checksums in hardware.
  • Thread safety: lwIP's core is single-threaded; call it only from its own thread or with the provided locking.

Pitfall: Nagle's algorithm delays small TCP sends to combine them, and combined with delayed ACKs on the receiver it can add 40 to 200 ms latency to request-response protocols. Set TCP_NODELAY for interactive traffic.

Interview question: Explain the TCP three-way handshake and why it is needed.

Answer: The client sends SYN with its initial sequence number, the server replies SYN-ACK with its own initial sequence number and acknowledges the client's, and the client acknowledges the server's. After this both sides know the other is reachable and have agreed on starting sequence numbers, which are needed to order bytes, detect loss and duplicates, and reject stale packets from old connections. Random initial sequence numbers also make spoofing harder.

Interview question: An embedded TCP client only achieves 20 KB/s over a fast network. What limits it?

Answer: Most likely the TCP window: throughput is capped at roughly window size divided by round-trip time, and small embedded stacks often use 2 to 4 KB receive windows and few buffers. Check the advertised window and MSS, the number of pbufs and whether packets are dropped for lack of buffers, Nagle and delayed-ACK interaction for request-response traffic, retransmissions in a packet capture, and whether the application reads from or writes to the socket slowly, for example because a slow flash write blocks the receiver.

Build it: accept only the packets meant for the monitor

This is step 1 of the module project, an office air-quality monitor: a CO2, temperature and humidity sensor on the building network that reports to a cloud service and takes commands from it. It runs a small TCP/IP stack with no operating system underneath, so the code that looks at each received packet first is yours. Anything it passes on, the rest of the stack trusts.

Lab: Check each received IPv4 header

Write the first check the stack runs on every packet the Ethernet driver hands over.

  • ip_checksum(data, len) returns the Internet checksum: add the data as 16-bit big-endian words (pad an odd last byte with a zero byte), fold any carries above bit 15 back into the low 16 bits until none are left, then invert. Run over a header with its checksum field in place, a correct header gives 0.
  • ip_accept(pkt, len, my_ip, info) returns, checking in this order:
  • IP_BAD when len is under 20, the version is not 4, the header length (IHL, in 4-byte words) is under 5 or longer than len, the total length field is shorter than the header or longer than len, or the header checksum is wrong;
  • IP_FRAGMENT when the more-fragments flag (0x2000 in bytes 6 and 7) or the fragment offset (0x1FFF) is set: this stack does not reassemble;
  • IP_NOT_FOR_US when the destination is neither my_ip nor the broadcast address 255.255.255.255;
  • otherwise IP_OK, after filling info: the source address, the protocol, where the payload starts and how long it is.

Short Ethernet frames are padded to 60 bytes, so len can be larger than the packet: the payload length comes from the total length field, never from len.

Going deeper

Interview question: Why might a smart doorbell use both TCP and UDP?

Answer: TCP for reliable, ordered transfers where every byte matters (configuration, firmware updates, event uploads), and UDP for live video and audio, where a late packet is useless and retransmission would add latency; a protocol on top (RTP, WebRTC) adds sequence numbers and handles loss. NAT traversal and keepalives keep it reachable from the owner's phone.

Interview question: What is the maximum segment size, and how does it relate to the MTU?

Answer: The MTU is the largest IP packet a link carries (1500 bytes on Ethernet). The MSS is the largest TCP payload, typically the MTU minus the IP and TCP headers, 1460 bytes for IPv4 on Ethernet; each side announces its MSS in the handshake. Sending larger segments would require IP fragmentation, which hurts performance and reliability, so stacks size segments to the MSS, and embedded stacks may advertise a smaller MSS to save buffer memory.

Interview question: How does NAT affect devices that must receive incoming connections?

Answer: A NAT router maps many private addresses to one public address and only forwards inbound packets that match a mapping created by outbound traffic. A device behind it cannot be reached by an unsolicited inbound connection. So IoT devices make an outbound connection to a broker or server and keep it alive with keep-alives shorter than the NAT's idle timeout, receiving commands over that connection.

Explain it: In your own words, explain how TCP recovers from a lost packet.

Answer: Every byte sent has a sequence number, and the receiver acknowledges the highest byte it has received in order. If a segment is lost, the receiver keeps acknowledging the last in-order byte, so the sender sees duplicate acknowledgements; after three it retransmits the missing segment at once. If no acknowledgement arrives at all within the retransmission timeout, which is based on the measured round-trip time, the sender retransmits and doubles the timeout. The receiver holds out-of-order data and delivers it to the application in order once the gap is filled.