JustTrying JustTrying - 7 days ago 5
C Question

How many bytes can I write at once on a TCP socket?

As the title says, is there a limit to the number of bytes that can be written at once on a connection-oriented socket?

If I want to send a buffer of, for example, 1024 bytes, can I use a

write(tcp_socket, buffer, 1024);


or should I use multiple
write()
calls with a lower amount of bytes for each one?

Answer

write() does not guarantee that all bytes will be written so multiple calls to write() are required. From man write:

The number of bytes written may be less than count if, for example, there is insufficient space on the underlying physical medium, or the RLIMIT_FSIZE resource limit is encountered (see setrlimit(2)), or the call was interrupted by a signal handler after having written less than count bytes. (See also pipe(7).)

write() returns the number of bytes written so a running total of the bytes written must be maintained and used as an index into buffer and to calculate the number of remaining bytes to be written:

ssize_t total_bytes_written = 0;
while (total_bytes_written != 1024)
{
    assert(total_bytes_written < 1024);
    ssize_t bytes_written = write(tcp_socket,
                                  &buffer[total_bytes_written],
                                  1024 - total_bytes_written);
    if (bytes_written == -1)
    {
        /* Report failure and exit. */
        break;
    }
    total_bytes_written += bytes_written;
}