Networking & IoT · Interview question

Why must you loop on send() and recv() with TCP?

A strong answer

Because TCP is a byte stream with no message boundaries and the calls are not guaranteed to transfer the full amount you asked for. send() may accept only part of your buffer, the kernel's send buffer might be partly full, so it returns the number of bytes it actually queued, and you must call it again for the remainder, looping until your whole message is sent. recv() returns whatever bytes are available right now, which may be fewer than a complete application message (or several messages glued together), because TCP can segment and coalesce data based on buffering, MTU, and Nagle's algorithm. So an application that assumes one send equals one recv, or that recv returns a whole message, will mis-frame its protocol, read a partial header, split a value, or merge two messages. The correct pattern is to loop send until all bytes are written, and to accumulate received bytes into a buffer, applying your own framing (a length prefix or delimiter) to know when a complete message has arrived before parsing. You also interpret the return values precisely: recv returning 0 means the peer closed the connection (end of stream), and a negative value is an error (or EWOULDBLOCK on a non-blocking socket), not "no data, retry blindly."

What a weak answer sounds like

You know the answer. Do you know what gets you dinged?

Pro breaks down the answer most candidates actually give to this question — and the specific reason an interviewer marks it down. It’s the difference between sounding correct and sounding senior, on all 472 questions.

From the lesson

Sockets

The programming interface to TCP/UDP: the BSD socket calls (socket/connect/send/recv, bind/listen/accept), client and server flows, byte order, and the partial-I/O and blocking traps on an MCU.

More Sockets questions

Browse all 472 interview questions
Why must you loop on send() and recv() with TCP? | EmbeddedPrep.io