mpr
mpr

Reputation: 3378

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.

Upvotes: 4

Views: 968

Answers (2)

SergeyA
SergeyA

Reputation: 62563

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.

Upvotes: 4

Jeremy Friesner
Jeremy Friesner

Reputation: 73051

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?

Sure, call select() and see if the socket selects as ready-for-write. If it doesn't, that means the socket's outgoing buffer is full. (You can use select()'s timeout parameter to force the select() call to return immediately, if you don't want it to block until a socket is ready to read/write/etc)

Upvotes: -1

Related Questions