(10) 如何获取 linux 系统上的 TCP 、 UDP 套接字的收发缓存的默认大小,以及代码范例

(1) 先介绍下后面的代码里要用到的基础函数:

++ 以及:

++

(2) 接着给出现代版的 读写 socket 参数的系统函数 :

++ 以及:

(3) 给出 一言的 范例代码,获取当代 linux 系统的 tcp 套接字的缓存大小:

c 复制代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/types.h>

int main() 
{
    int sockfd , sndbuf, rcvbuf ;        socklen_t optlen;
    
    sockfd = socket(AF_INET, SOCK_STREAM, 0);  // 创建一个 TCP 套接字
    if (sockfd < 0) {   perror("socket");    exit(EXIT_FAILURE);  }

    // 获取发送缓存大小
    optlen = sizeof(sndbuf);
    if (getsockopt(sockfd, SOL_SOCKET, SO_SNDBUF, (void *)&sndbuf, &optlen) < 0) {
        perror("getsockopt SO_SNDBUF");
        close(sockfd);       exit(EXIT_FAILURE);
    }
    printf("Send buffer size: %d bytes\n", sndbuf);

    // 获取接收缓存大小
    optlen = sizeof(rcvbuf);
    if (getsockopt(sockfd, SOL_SOCKET, SO_RCVBUF, (void *)&rcvbuf, &optlen) < 0) {
        perror("getsockopt SO_RCVBUF");
        close(sockfd);        exit(EXIT_FAILURE);
    }
    printf("Receive buffer size: %d bytes\n", rcvbuf);

    close(sockfd);  // 关闭套接字

    return 0;
}

++ 给出 ubantu 的打印结果( 跟 30 年前的 伯克利系统里的缓存设置,已经有了很大的差别)

++ 以下是 30 年前的 tcp/ip 协议的系统缓存设置:

(4)

谢谢

相关推荐
摇滚侠15 小时前
Linux CentOS7 rpm 安装 MySQL 5.7
linux·运维·mysql
bush415 小时前
嵌入式linux学习记录十四、术语
linux·嵌入式
载数而行52016 小时前
Linux 11 动态监控指令top
linux
treesforest17 小时前
AI安全系统如何识别异常访问?IP风险识别正在成为关键能力
网络·人工智能·tcp/ip·安全·web安全
不会C语言的男孩17 小时前
Linux 系统编程 · 第 8 章:进程基础
linux·c语言
古城小栈17 小时前
Unix 与 Linux 异同小叙
linux·服务器·unix
凡人叶枫18 小时前
Effective C++ 条款42:了解 typename 的双重意义
java·linux·服务器·c++
2601_9618752419 小时前
决战申论100题2026|最新|范文
linux·容器·centos·debian·ssh·fabric·vagrant
java_cj19 小时前
深入kube-apiserver认证机制:从Bearer Token到mTLS的完整认证链解析
linux·运维·服务器·云原生·容器·kubernetes
lsyeei19 小时前
linux 系统目录详解
linux·运维·服务器