Lesson 8 of 18 The System Calls

send(), recv(), sendto(), recvfrom()

Moving data over sockets in C: send() and recv() for TCP, sendto() and recvfrom() for UDP, return values, flags, SIGPIPE and detecting a closed peer.

40-50 min beginner 0/18 lessons done
Course contents Lesson 8 of 18 · 0 done
On this page (9 sections)
  1. What you will learn
  2. send() and recv() for connected sockets
  3. sendto() and recvfrom() for datagrams
  4. Flags
  5. SIGPIPE: the silent killer
  6. read() and write() work too
  7. Key takeaways
  8. Exercises
  9. Quiz

What you will learn

  • The four data-transfer calls and when to use each.
  • How to read every possible return value, including 0.
  • Useful flags: MSG_PEEK, MSG_WAITALL, MSG_DONTWAIT, MSG_NOSIGNAL.
  • Why writing to a closed connection can kill your program, and how to prevent it.

send() and recv() for connected sockets

ssize_t send(int sockfd, const void *buf, size_t len, int flags);
ssize_t recv(int sockfd, void *buf, size_t len, int flags);

Use them on a connected TCP socket (or a UDP socket after connect()).

send() returns the number of bytes the kernel accepted, which can be less than len. The kernel copies data into the socket’s send buffer; if the buffer only has room for part of it, you get a short count and must send the rest yourself. Small sends on a quiet connection usually go through whole, which is exactly why this bug hides until production. The send_all() loop in lesson 15 handles it.

recv() returns:

ReturnMeaningWhat to do
> 0That many bytes were placed in bufProcess them; more may follow
0The peer closed its side in an orderly way (end of stream)Stop reading; close your socket
-1Error; check errnoEINTR: retry. EAGAIN: no data yet (non-blocking). Others: close

The 0 return is the one and only way a TCP reader learns that the other side has finished. That makes “how do I tell the remote side closed the connection?” a one-line answer: recv() returned 0.

recv() never adds a terminating '\0'. If you want to treat the data as a C string, reserve a byte and add it yourself:

char buf[256];
ssize_t n = recv(fd, buf, sizeof buf - 1, 0);
if (n > 0) {
    buf[n] = '\0';
    printf("got: %s\n", buf);
}

sendto() and recvfrom() for datagrams

ssize_t sendto(int sockfd, const void *buf, size_t len, int flags,
               const struct sockaddr *dest_addr, socklen_t addrlen);

ssize_t recvfrom(int sockfd, void *buf, size_t len, int flags,
                 struct sockaddr *src_addr, socklen_t *addrlen);

An unconnected UDP socket has no fixed peer, so each sendto() names its destination and each recvfrom() tells you who sent the datagram (pass a sockaddr_storage and its size, as in lesson 4).

Datagram rules worth memorising:

  • One sendto() = one datagram. One recvfrom() = one datagram.
  • If your buffer is smaller than the datagram, the rest is discarded, not saved for later.
  • A datagram larger than the path’s MTU (often around 1500 bytes on Ethernet) gets fragmented at the IP layer; losing any fragment loses the whole datagram. Keep UDP payloads small, ideally under about 1200 bytes.
  • recvfrom() returning 0 means you received an empty datagram, not that anybody closed anything. UDP has no connection to close.

The UDP lesson builds a full sender and receiver.

Flags

Pass 0 normally. The useful flags:

FlagCallsEffect
MSG_PEEKrecvLook at waiting data without removing it from the queue
MSG_WAITALLrecvBlock until the full len arrives (still returns less on close, error or signal)
MSG_DONTWAITbothMake this one call non-blocking
MSG_NOSIGNALsend (Linux)Don’t raise SIGPIPE if the peer has gone; return EPIPE instead
MSG_OOBbothTCP urgent data; legacy, avoid in new protocols

SIGPIPE: the silent killer

If you send() on a TCP connection that the peer has already closed (and reset), the kernel sends your process the SIGPIPE signal. Its default action is to terminate the process without any message. A server that dies whenever a client disconnects mid-reply is usually suffering from this.

Two fixes; pick one:

/* 1. Ignore the signal process-wide; send() then fails with errno == EPIPE. */
signal(SIGPIPE, SIG_IGN);

/* 2. Or, on Linux, suppress it per call. */
send(fd, buf, len, MSG_NOSIGNAL);

(On macOS and BSD, MSG_NOSIGNAL may be missing; set the socket option SO_NOSIGPIPE instead, or ignore the signal.)

read() and write() work too

Since sockets are descriptors, read(fd, buf, n) is the same as recv(fd, buf, n, 0) and write() is the same as send() with no flags. Using send/recv makes the intent clear and gives you flags, so this course prefers them.

Key takeaways

  • send() may accept fewer bytes than you asked; always check and loop.
  • recv() > 0 is data, 0 is an orderly close, -1 is an error to examine.
  • UDP: one call, one datagram; oversized datagrams are truncated; keep them small.
  • Protect servers from SIGPIPE with SIG_IGN or MSG_NOSIGNAL.

Exercises

  1. Write a client that sends 10 MB in a single send() call to nc -l 9000 > /dev/null and prints what send() returned. Repeat with the receiver paused (Ctrl-Z) to see blocking.
  2. Using MSG_PEEK, write a function that checks whether the next bytes waiting on a socket begin with "GET " without consuming them.
  3. Make a server that writes to a client after the client exits. Observe the crash, then fix it both ways shown above.

Quiz

  1. recv() returned 0 on a TCP socket. What happened?
  2. A UDP datagram of 900 bytes arrives and you call recvfrom() with a 512-byte buffer. What happens to the other 388 bytes?
  3. Why might a server process vanish with no error message when a client disconnects?
Show answers
  1. The peer closed its sending side (or the whole connection) normally. No more data will arrive.
  2. They are discarded. Datagrams are delivered whole or truncated; there is no “rest” to read later. (MSG_TRUNC on Linux can report the real size.)
  3. It wrote to a closed connection and received SIGPIPE, whose default action terminates the process.

Finished this lesson?

Mark it complete to track your progress (saved in this browser).