Search code examples
linuxsocketstcp

does recv always return the same amount of data passed to send?


If I have two sockets (AF_INET, SOCK_STREAM, IPPROTO_IPV4) connected together and I issue a send() of 32 bytes on one end, is the recv() operation that reads the data on the other end guaranteed to return the same amount of data in a single call?


Solution

  • No, there is no such guarantee. In fact, by default, multiple consecutive short writes will be combined into a single network packet, which will be received in a single recv(). (This is known as Nagle's algorithm.)

    If the data you are transmitting needs to be framed in a specific way, you will need to include data to define that framing as part of the data you transmit. One simple approach is to delimit your data with a special character, like a newline or a null byte; another is to transmit the length of each frame before its data. (There are many other ways to frame data; these are just a few ideas to get started with.)