Does send() always send whole buffer?


send() shall return the number of bytes sent or error code, but all examples that I found check it only with error codes, but not with the number of bytes sent.

//typical example
int cnt=send(s,query,strlen(query),0);
if (cnt < 0) return(NULL);
//Hey, what about cnt < strlen(query)?


Q: Does “send()” always return the whole buffer?

A: No, not necessarily.

From Beej’s Guide:

send() returns the number of bytes actually sent out—this might be
less than the number you told it to send! See, sometimes you tell it
to send a whole gob of data and it just can’t handle it. It’ll fire
off as much of the data as it can, and trust you to send the rest
later. Remember, if the value returned by send() doesn’t match the
value in len, it’s up to you to send the rest of the string. The good
news is this: if the packet is small (less than 1K or so) it will
probably manage to send the whole thing all in one go. Again, -1 is
returned on error, and errno is set to the error number.

Q: Does “recv()” always read the whole buffer?

A: No, absolutely not. You should never assume the buffer you’ve received is “the whole message”. Or assume the message you receive is from one, single message.

Here’s a good, short explanation. It’s for Microsoft/C#, but it’s applicable to all sockets I/O, in any language:

Answered By – paulsm4

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published