fun fact about TCP

There’s one less-than-expected thing about TCP: even if you provide a small buffer to recv() and the other side sends exactly the same amount of data in the send() call, there’s no guarantee that the data is received in one call.

Take for example Python:

# sock is a socket.socket(), already connected
data = socket.recv(4)
length = struct.unpack('=l', data)[0]  # this might fail!

There are two ways to mitigate it:

  • really portable way: receive in a loop, until all data are received – but beware of recv() returning b'' – this means there’s an error in the communication
  • Linux/Unix way: use MSG_WAITALL flag to force recv() to block until whole buffer is filled

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.