Read a socket option back with getsockopt and socklen_t
Read a socket option back with getsockopt() in C on POSIX, and set the socklen_t length argument first because the kernel treats it as value-result.
This is how you ask a socket what it is currently set to. getsockopt() takes the option's size in a socklen_t and writes the real size back, so you must initialise it before the call.
#include <stdio.h>
#include <sys/socket.h>
int main(void)
{
int fd = socket(AF_INET, SOCK_STREAM, 0);
int sndbuf = 0;
socklen_t len = sizeof sndbuf;
if (getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &sndbuf, &len) < 0) {
perror("getsockopt");
return 1;
}
printf("SO_SNDBUF=%d len=%u\n", sndbuf, (unsigned)len);
return 0;
}SO_SNDBUF=87040 len=4On Linux 6.8 a fresh TCP socket reports the default from net.ipv4.tcp_wmem, here 87040 bytes, though a tuned host prints a different number. The len argument is both input and output: pass a buffer of the wrong size, such as sizeof(long) for an int option, and the kernel may truncate or fail with EINVAL.
One gotcha worth knowing: after you set SO_SNDBUF or SO_RCVBUF, getsockopt() returns double what you asked for, because Linux reserves space for bookkeeping overhead. See socket(7). A returned value is the live setting, not a promise about the connection's behavior, since TCP autotuning can grow buffers on its own.