Search code examples
socketstcpbuffer

Receive buffer size for tcp/ip sockets


What's the maximum data size one should expect in a receive operation? The data that has to be sent is very large, but at some point there will be packet fragmentation I guess?


Solution

  • There is something like maximum network packet size:

    MTU

    this indicates the max size off the low level buffer (3 iso/osi layer IP) during data transfer over network (not loopback). Which is typically 1492 in Ethernet networks.

    So it's worth to optimize data transfer to size of this amount.

    (there are also so called Jumbo frames which breaks this rule, but there must be software/hardware which accepts that)

    However simple recv() on socket, can return more bytes than MTU. So you need to transfer first packet with the size of the rest data.

    size = recv(512) // size should came in one shot 
    while( count(data) == size) // the rest of actual data can came sliced, so You should receive until size
        data[offset] = recv(size)