Search code examples
csocketstcpmjpeg

Is it possible to read the number of bytes buffered for a TCP write socket?


I have an app that uses the civetweb (formerly mongoose) HTTP server library to create an MJPEG stream. Works fine when my MJPEG settings match the bandwidth profile of the network the clients are connecting from, but occasionally we have a low bandwidth connection that I'd like to accommodate by dropping frames.

Right now when I call mg_write(), the mongoose library calls send() like this:

send(sock, buf + sent, (size_t) k, MSG_NOSIGNAL);

What I'd like to do is check the outgoing buffer of the socket, and if it's full, skip a frame. Is there any way to check this at the application level?

EDIT: Just a side note for MJPEG folks, these TCP buffers are pretty large and what I actually ended up measuring was simply if there were any bytes present in the buffer at all. If there were more than zero I skipped a frame.


Solution

  • You can use ioctl for this on Linux (and similar interfaces on other systems):

    #include <linux/sockios.h>
    
    size_t sb_sz = sizeof(sock_buffer_size);
    ioctl(sock, SIOCOUTQ, &bytes_in_queue);
    getsockopt(sock, SOL_SOCKET, SO_SNDBUF, &sock_buffer_size, &sb_sz);
    size_t bytes_available = sock_buffer_size - bytes_in_queue;
    

    Note that it still does not give you 100% guarantee that the write will succeed in full, but it gives you pretty good chance of it.