Try Embedded

Sockets API basics

Socket lifecycle, TCP versus UDP, blocking and select/poll.

The universal network API

The BSD sockets API, from 1980s Unix, is how almost every program talks to a network: Linux, Windows, macOS, and on microcontrollers through lwIP's socket layer, Zephyr, FreeRTOS+TCP and modem libraries that mimic it. Learning it once covers all of them.

A socket is an endpoint for communication, identified by a protocol, a local address and port, and (when connected) a remote address and port.

TCP versus UDP

TCP (SOCK_STREAM)UDP (SOCK_DGRAM)
ConnectionYes: handshake firstNo
DeliveryReliable, in order, no duplicatesBest effort: may be lost, reordered, duplicated
Data modelByte stream: no message boundariesDatagrams: each send is one message
Flow and congestion controlYesNo
OverheadHigher (header, ACKs, state)Low
Used byHTTP, MQTT, TLSDNS, NTP, CoAP, DHCP, streaming, discovery

The TCP client lifecycle

int s = socket(AF_INET, SOCK_STREAM, 0);

struct sockaddr_in srv = { .sin_family = AF_INET, .sin_port = htons(1883) };
inet_pton(AF_INET, "192.168.1.10", &srv.sin_addr);

if (connect(s, (struct sockaddr *)&srv, sizeof srv) < 0) { /* handle error */ }

send(s, request, request_len, 0);
ssize_t n = recv(s, buf, sizeof buf, 0);   /* 0 = peer closed, <0 = error */

close(s);

The TCP server lifecycle

int ls = socket(AF_INET, SOCK_STREAM, 0);
int yes = 1;
setsockopt(ls, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof yes);   /* restart without waiting for TIME_WAIT */

struct sockaddr_in addr = { .sin_family = AF_INET, .sin_port = htons(8080), .sin_addr.s_addr = htonl(INADDR_ANY) };
bind(ls, (struct sockaddr *)&addr, sizeof addr);
listen(ls, 4);                                                /* backlog of pending connections */

for (;;) {
  int c = accept(ls, NULL, NULL);                             /* blocks until a client connects */
  handle_client(c);
  close(c);
}

socket → bind → listen → accept (returns a new socket per client) → recv/send → close.

UDP is simpler: socket, optionally bind, then sendto and recvfrom with the peer address each time.

TCP is a stream: framing is your job

The most common networking bug: assuming one send arrives as one recv. TCP may split a send across several receives, or merge several sends into one. Every TCP protocol needs framing: a length prefix, a delimiter (newline in HTTP headers), or a fixed size. And send may send fewer bytes than asked.

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

/* Length-prefixed framing: 2-byte big-endian length, then the payload.
   feed() is given bytes in whatever chunks recv() produced. */
static uint8_t acc[64];
static size_t have;

static void feed(const uint8_t *data, size_t len) {
  memcpy(acc + have, data, len);
  have += len;
  for (;;) {
    if (have < 2) return;
    size_t need = (size_t)((acc[0] << 8) | acc[1]);
    if (have < 2 + need) return;                      /* wait for the rest */
    printf("message: %.*s\n", (int)need, (const char *)acc + 2);
    memmove(acc, acc + 2 + need, have - 2 - need);    /* keep any following bytes */
    have -= 2 + need;
  }
}

int main(void) {
  /* Two messages, "hello" and "sensor=21", arriving split across three recv() calls. */
  const uint8_t chunk1[] = { 0, 5, 'h', 'e' };
  const uint8_t chunk2[] = { 'l', 'l', 'o', 0, 9, 's', 'e', 'n' };
  const uint8_t chunk3[] = { 's', 'o', 'r', '=', '2', '1' };
  feed(chunk1, sizeof chunk1);
  feed(chunk2, sizeof chunk2);
  feed(chunk3, sizeof chunk3);
  return 0;
}

The sending side needs the mirror: loop until all bytes are sent.

Blocking, non-blocking and multiplexing

By default connect, accept, recv and send block. Options for handling several sockets or doing other work:

ApproachHowEmbedded fit
Blocking + one task per connectionEach task blocks on its own socketSimple with an RTOS; RAM per task
TimeoutsSO_RCVTIMEO, SO_SNDTIMEOAlways set them; never block forever
Non-blockingfcntl(s, F_SETFL, O_NONBLOCK); calls return EAGAIN/EWOULDBLOCKPolling loop; wastes CPU unless combined below
select() / poll()Wait until any of several sockets is readable or writable, with a timeoutOne task serves many sockets; supported by lwIP
epoll (Linux), callbacks (lwIP raw API)Event notificationHighest efficiency

A non-blocking connect returns EINPROGRESS; wait for writability with select, then check SO_ERROR for the result.

Errors you must handle

  • recv returning 0: the peer closed the connection cleanly.
  • ECONNRESET: the peer reset the connection.
  • EPIPE / SIGPIPE on Linux when sending to a closed socket: use MSG_NOSIGNAL or ignore the signal.
  • ETIMEDOUT, EHOSTUNREACH: network problems; retry with backoff.
  • DNS failures from getaddrinfo: retry later; cache results.

Keep-alive and dead connections

A TCP connection whose peer vanished (power loss, NAT timeout) can look open forever: nothing is received, and nothing errors until you send. Detect it with application-level heartbeats (MQTT's keep-alive) or TCP keep-alive (SO_KEEPALIVE with tuned intervals), and set receive timeouts.

Pitfall: htons/htonl are needed for ports and addresses in socket structures, because the network uses big-endian order and most MCUs are little-endian. Forgetting them connects to port 2823 instead of 1803, which looks like "connection refused".

Interview question: When would you choose UDP over TCP on an embedded device?

Answer: When messages are small and self-contained, latency matters more than guaranteed delivery, or the protocol already handles reliability: periodic sensor readings where a newer value replaces a lost one, discovery and broadcast or multicast, DNS, NTP, CoAP, and real-time audio or video. UDP also suits constrained or lossy links (NB-IoT, 6LoWPAN) because there is no connection state or handshake. If you need reliability, you then add sequence numbers, acknowledgements and retries yourself, or use CoAP's confirmable messages.

Interview question: How would one task serve several TCP connections without blocking on any of them?

Answer: Put the sockets in non-blocking mode and use select() or poll() with a timeout on the listening socket and all client sockets. When select reports a socket readable, call accept or recv on it; when writable, continue sending pending data. Keep a per-connection state struct with input and output buffers and the framing state. The timeout lets the task do periodic work and close idle connections. On lwIP or Zephyr this is supported directly; alternatively use the stack's callback API.

Build it: commands from the cloud, however TCP cuts them

This is step 2 of the module project, the office air-quality monitor. The cloud service keeps a TCP connection open to each monitor and sends it commands ("set the report interval", "turn the warning LED on"), each as a frame: a 2-byte big-endian length, then that many bytes. It works on the bench, where every recv() happens to return one whole frame. On the office network it does not, and the monitor sends its readings back the same way, through a socket that may take only part of them.

Lab: Frame a TCP stream, and send all of it

Receiving. rx_feed(rx, data, n) is called with whatever one recv() returned: part of a frame, several frames, or the end of one and the start of the next. Collect bytes in rx and call on_frame(payload, len) once for each complete frame, in order. Return the number of frames delivered by this call. A length of 0 or over MAX_FRAME means the stream is out of step and cannot be trusted: return -1 at once (the caller closes the connection) and leave rx empty.

Sending. send_all(data, n) must hand over all n bytes. sock_send() (a non-blocking socket) may accept fewer bytes than asked; it returns WOULD_BLOCK when its buffer is full, and then you call wait_writable() and try again; it returns CONN_ERROR when the connection has failed. Return n once everything is sent, or CONN_ERROR.

Going deeper

Interview question: How would you keep an industrial gateway's TCP connections alive and recover when they drop?

Answer: Use non-blocking sockets with timeouts, enable TCP keepalive (or application heartbeats) to detect dead peers, reconnect with exponential backoff and jitter, and buffer outgoing data while disconnected. Treat every send and receive error as a possible disconnection, and expose connection state in diagnostics.

Interview question: What is the TIME_WAIT state, and why does a restarting server need SO_REUSEADDR?

Answer: After a TCP connection closes, the side that closed first keeps the connection in TIME_WAIT for twice the maximum segment lifetime so late packets cannot be mistaken for a new connection with the same addresses and ports. A server that restarts quickly may find its listening port still tied to such connections and bind fails; SO_REUSEADDR allows binding the port anyway.

Interview question: Why should every network call on a device have a timeout?

Answer: Networks fail silently: a peer can vanish (power loss, NAT timeout) without the connection ever closing, so a blocking recv or connect can wait forever, hanging the task and eventually the device. Timeouts (SO_RCVTIMEO, SO_SNDTIMEO, non-blocking with select, application heartbeats) bound every wait, letting the code reconnect and recover.

Explain it: In your own words, explain why a TCP receiver must frame messages itself.

Answer: TCP delivers a reliable stream of bytes, not separate messages: the sender's writes can be split across several reads at the receiver or merged into one, depending on buffering, segment sizes and timing. So a receiver that assumes one recv returns exactly one message will eventually see half messages or two messages joined. The application protocol must mark boundaries itself, with a length prefix, a delimiter or fixed-size records, and the receiver must accumulate bytes until a complete message is present.