Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

recv receiving not whole data sometime

I have following issue: here is the chunk of code:

void get_all_buf(int sock, std::string & inStr) {
    int n = 1;
    char c;
    char temp[1024*1024]; 

    bzero(temp, sizeof(temp));

    n = recv(sock, temp, sizeof(temp), 0);

    inStr = temp;
};

but sometimes recv returning not whole data (data length always less then sizeof(temp)), only its part. Write side always sends me whole data (I got it with sniffer). What matter? Thx.

P.S. I know, good manner suggests me to check n (if (n < 0) perror ("error while receiving data")), but it doesn't matter now - it's not reason of my problem.

P.S.2 I've forgot - it's blocking socket.

like image 531
milo Avatar asked Nov 30 '22 09:11

milo


1 Answers

The TCP standard allows for fragmentation of data packets. In practice this doesn't happen with small data packets of a few hundred bytes or so, but a megabyte of data is almost certain to get fragmented.

Secondly, when you say the sniffer says all the data gets sent, in one packet or in many?

Good network programming practice requires you to not assume that messages arrive in singular chunks. Two sequential messages can arrive as one packet (in theory but almost never in practice) and even if they arrive in multiple packets can be read as a single read. One message can get fragmented into multiple packets and they might not all arrive at once which is probably what you are seeing.

Your program should buffer all its reads and have a mechanism to determine when a whole message has arrived, either via a delimiter (e.g. HTTP headers which are delimited with CRLFCRLF) or by a byte count (e.g. HTTP bodies where the length is specified in the header) or by closing the connection to indicate the end of the data (e.g. HTTP bodies when the content length isn't specified in the header). There may be other mechanisms too.

like image 109
AlastairG Avatar answered Dec 05 '22 05:12

AlastairG