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:
| Return | Meaning | What to do |
|---|---|---|
> 0 | That many bytes were placed in buf | Process them; more may follow |
0 | The peer closed its side in an orderly way (end of stream) | Stop reading; close your socket |
-1 | Error; check errno | EINTR: 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. Onerecvfrom()= 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:
| Flag | Calls | Effect |
|---|---|---|
MSG_PEEK | recv | Look at waiting data without removing it from the queue |
MSG_WAITALL | recv | Block until the full len arrives (still returns less on close, error or signal) |
MSG_DONTWAIT | both | Make this one call non-blocking |
MSG_NOSIGNAL | send (Linux) | Don’t raise SIGPIPE if the peer has gone; return EPIPE instead |
MSG_OOB | both | TCP 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
SIGPIPEwithSIG_IGNorMSG_NOSIGNAL.
Exercises
- Write a client that sends 10 MB in a single
send()call tonc -l 9000 > /dev/nulland prints whatsend()returned. Repeat with the receiver paused (Ctrl-Z) to see blocking. - Using
MSG_PEEK, write a function that checks whether the next bytes waiting on a socket begin with"GET "without consuming them. - Make a server that writes to a client after the client exits. Observe the crash, then fix it both ways shown above.
Quiz
recv()returned 0 on a TCP socket. What happened?- A UDP datagram of 900 bytes arrives and you call
recvfrom()with a 512-byte buffer. What happens to the other 388 bytes? - Why might a server process vanish with no error message when a client disconnects?
Show answers
- The peer closed its sending side (or the whole connection) normally. No more data will arrive.
- They are discarded. Datagrams are delivered whole or truncated; there is no “rest” to read later. (
MSG_TRUNCon Linux can report the real size.) - It wrote to a closed connection and received
SIGPIPE, whose default action terminates the process.