3

In linux, or windows socket programming

I know that read returns a value which indicates the number of successfully received number of bytes.

this return value might be less than requested length. (i.e, read(sd, buf, 100) might return 50 if the receive buffer only has 50 bytes)

is it possible that

send(sd, buf, 100);

returns a value between 1~99?? if it is, what is the occasion? I want to know specific example situation.

thank you in advance

1 Answer 1

6

See the man pages, or the MSDN documentation if you are talking about Winsock, for the offical specification.

In practice, send() in blocking mode sends all the data, regardless of what the documentation says, unless there was an error, in which case nothing is sent.

In non-blocking mode, it sends whatever will fit into the socket send buffer and returns that length if > 0. If the socket send buffer is full, it returns -1 with errno = EWOULDBLOCK/EAGAIN.

Sign up to request clarification or add additional context in comments.

5 Comments

thank you that is exactly what I assumed. you confirmed it, thank you
I haven't tested it, but I imagine that if you were sending very large buffers (e.g. more than 65KB per send() call) via blocking I/O, that it would be possible for send() to send part of the data, and then encounter an error (e.g. remote peer closed the connection). In that scenario I think the only useful way for send() to behave would be to return the number of bytes sent, which would be less than the buffer size. This doesn't happen often in practice only because most programs don't try to send so much data in one call.
@JeremyFriesner It is possible according to the specification. In practice it doesn't happen, and not because 'most programs don't try to send so much data', but because that's the way send() is implemented in all kernels.
Hmm, okay then, what does send() do if it has sent 200KB of a 800KB buffer and then the receiving application closes its end of the socket? Will send() return 0 at that point and pretend that it didn't successfully send anything? I guess I will have to try it for myself and see...
Okay, I tried it (by sending a 20MB buffer over TCP to another program on localhost via single send() call), and I verified that EJP is correct -- at least under MacOS/X 10.8.2, it doesn't matter how many bytes actually got to the receiver, blocking send() will still return -1 if it couldn't send the entire buffer. Not the way I would have implemented it, but that's the way it is. :P

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.