Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does send() always send whole buffer?

Tags:

c

linux

sockets

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)?
like image 957
Nelson Tatius Avatar asked Sep 29 '12 22:09

Nelson Tatius


1 Answers

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

A: No, not necessarily.

From Beej's Guide: * http://beej.us/guide/bgnet/html/multi/syscalls.html#sendrecv

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:

  • http://blogs.msdn.com/b/joncole/archive/2006/03/20/simple-message-framing-sample-for-tcp-socket.aspx
like image 100
paulsm4 Avatar answered Sep 29 '22 23:09

paulsm4