Querying maximum socket send buffer size in C?

后端 未结 2 1826
被撕碎了的回忆
被撕碎了的回忆 2021-01-24 04:53

I know I can cat /proc/sys/net/core/wmem_max to get the maximum size for SO_SNDBUF on a socket, but is there an easy way to query that value in C without going through the klud

相关标签:
2条回答
  • 2021-01-24 04:59

    To get the value of the net.ipv4.tcp_wmem sysctl, you need to parse it out of the /proc file representing that sysctl (there really is no better way on Linux, and the sysctl system call has long since been deprecated.)

    Something like:

    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
    

    For a particular socket, you can get the current remaining buffer with

       

      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);
    
    0 讨论(0)
  • 2021-01-24 05:11

    Couldn't you invoke the sysctl command on the shell (use system() or popen/pclose()) to get this information...at least avoids opening a file but may be equivalent in overall ugliness:

    system("sysctl -n net.ipv4.tcp_wmem");
    
    0 讨论(0)
提交回复
热议问题