[Libwebsockets] setting SO_SNDBUF socket option

Olivier Langlois olivier at olivierlanglois.net
Sun Feb 9 22:18:11 CET 2020

In roles/ws/client-ws.c,

There is the following code:

lwsl_info("Allocating client RX buffer %d\n", n);

#if !defined(LWS_WITH_ESP32)
        if (setsockopt(wsi->desc.sockfd, SOL_SOCKET, SO_SNDBUF,
                       (const char *)&n, sizeof n)) {
                lwsl_warn("Failed to set SNDBUF to %d", n);
                *cce = "HS: SO_SNDBUF failed";
                goto bail3;

1. I see an apparent contradiction between what the trace is saying and
what the code is doing.

The trace mention expanding the RX buffer but the code adjust the TX

2. According to 'man 7 tcp':

the socket buffer size must be set prior to the listen(2) or connect(2)
calls in order to have it take effect.

I went to the Linux kernel source code to validate this statement. I
don't want to become a kernel networking code expert but the conclusion
that I did draw from this review is that the kernel consider the
SO_SNDBUF and SO_RCVBUF options pretty much like hints only and the
actual buffer sizes are very dynamic to adapt to the actual conditions
(ie: accomodate a fast sender or get relief from memory pressure) and
can be above or below the SO_XXXBUF values.

The only time where I did witness a true concrete benefit from playing
with SO_SNDBUF was when I did reduce its value below the system default
value (and I was doing so before the listen() call...) for a server
serving thousands of concurrent connections. Doing so, did
significantly reduce the server memory usage.

That being said, if libwebsockets wants to be compliant with the Linux
TCP man page and ensure maximum portability, I would think that setting
socket buffer sizes in lws_client_connect_2() between the socket
creation and the call to connect would be a better place to do so.

As a sidenote, LWS_CALLBACK_WSI_CREATE seems to be the best spot for a
lws user to tweak some socket parameters if he needs to with
lws_get_socket_fd() while respecting the linux man documentation
requirements. I did study lws code to find out if it would allow me to
set SO_RCVBUF somehow!


More information about the Libwebsockets mailing list