Mackerel
Mackerel

Reputation: 107

Is send() function in TCP Guaranteed to arrive in order?

It is known that the return value of send() can be less than length, and it means a part of message, not whole, has arrived. I'm supposed to send 2 packets whose contents are "ABC" and "DEF" respectively, and their length is 3. I want to send "DEF" by send() after send() was called to transfer "ABC". However, there is a case that the return value of send() for "ABC" is less than its length, 3. I think there is opportunity that messages are not delivered in order. For example, if the return value for "ABC" is 2, received message is "ABDEF".

Is send() function in TCP Guaranteed to arrive in order?

Upvotes: 4

Views: 1131

Answers (1)

Malt
Malt

Reputation: 30285

First of all, send() itself doesn't guarantee anything, send() only writes the data you want to send over the network to the socket's buffer. There it's segmented (placed in TCP segments) by the operating system, which manages the reliability of the transmission. If the underlying buffer is full, then you'll get a return value that's lower that the number of bytes you wanted to write. This usually indicates that the buffer is not being emptied by the operating system fast enough, i.e. the rate at which you write data to the buffer is higher than the rate at which the data is being sent to the network (or read by the other party).

Second, TCP is a stream protocol, if you send() "ABC" and then "DEF", there's no guarantee about how that data will be segmented, it might end up in one packet, or in six packets. Exactly like writing data to a file.

Third, the network stack (TCP/IP implementation in the OS) guarantees in-order delivery, as well as the other nice things promised by TCP - reliability, congestion control, flow control, etc.

Upvotes: 4

Related Questions