Handling partial return from recv() TCP in C

Yes, you will need multiple recv() calls, until you have all data.

To know when that is, using the return status from recv() is no good – it only tells you how many bytes you have received, not how many bytes are available, as some may still be in transit.

It is better if the data you receive somehow encodes the length of the total data. Read as many data until you know what the length is, then read until you have received length data. To do that, various approaches are possible; the common one is to make a buffer large enough to hold all data once you know what the length is.

Another approach is to use fixed-size buffers, and always try to receive min(missing, bufsize), decreasing missing after each recv().

Leave a Comment