c - 在 C 中查询最大套接字发送缓冲区大小?

标签 c linux sockets

我知道我可以 cat/proc/sys/net/core/wmem_max 来获取套接字上 SO_SNDBUF 的最大大小,但是有没有一种简单的方法可以在 C 中查询该值而无需通过以下的笨拙的步骤打开文件、读取并转换为整数?

最佳答案

要获取 net.ipv4.tcp_wmem sysctl 的值,您需要从代表该 sysctl 的/proc 文件中解析它(在 Linux 上确实没有更好的方法,而且 sysctl 系统调用早已被弃用.)

类似于:

unsigned long wmem_min,wmem_default,wmem_max;
FILE *f = fopen("/proc/sys/net/ipv4/tcp_wmem", "r");
if(f == NULL)
   fail();
if(fscanf(f, "%lu %lu %lu", &wmem_min,&wmem_default,&wmem_max) != 3)
  fail();

fclose(f);
 ... use wmem_max

对于一个特定的套接字,你可以通过以下方式获取当前剩余的缓冲区

  socklen_t optlen;
  int send_buf, rc;
  optlen = sizeof(send_buf);
  //if getsockopt is successful, send_buf will hold the buffer size
  rc = getsockopt(sockfd, SOL_SOCKET, SO_SNDBUF, &send_buf, &optlen);

关于c - 在 C 中查询最大套接字发送缓冲区大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9980620/

相关文章:

c++ - 如何使用设置和使用 iconv 库

c - 从 POSIX I/O(open 等)迁移到 C 标准 I/O(fopen 等)

linux - 指定 GCC 输出二进制文件的预期 Linux 版本

multithreading - 阻止 SSL_read() 会在合作伙伴使用线程关闭连接时导致崩溃

javascript - 与其他模块共享 socket.io 会给出空对象

c - 使 C 程序更小

c - 在 C 中使用 fscanf

c - 从堆栈结构 C 释放指针

linux - 反转/开发/空

iphone - NSHost花费了很长时间