whatWhat whatWhat - 5 months ago 13
C Question

Handling partial return from recv() TCP in C

I've been reading through Beej's Guide to Network Programming to get a handle on TCP connections. In one of the samples the client code for a simple TCP stream client looks like:

if ((numbytes = recv(sockfd, buf, MAXDATASIZE-1, 0)) == -1) {

buf[numbytes] = '\0';

printf("Client: received '%s'\n", buf);


I've set the buffer to be smaller than the total number of bytes that I'm sending. I'm not quite sure how I can get the other bytes. Do I have to loop over
until I receive

*Note on the server side I'm also implementing his
function, so it should actually be sending everything to the client.

See also 6.1. A Simple Stream Server in the guide.


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().