(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)

谢谢

相关推荐
‎ദ്ദിᵔ.˛.ᵔ₎1 小时前
linux 进程信号(下)
linux·运维·服务器
skywalk81631 小时前
在FreeBSD系统的linux仿真环境下安装和使用kiro 这个亚马逊的AI agent
linux·人工智能·freebsd·kiro
Mikko71 小时前
Linux 磁盘满了但 du 找不到?LVM 扩容 df 不变?fstab 写错开不了机?三台真机实测磁盘排查
linux·运维·centos
Zooproxy全球IP代理1 小时前
海外代理IP纯净度评估:指标、检测与调度实践
网络协议·tcp/ip·php
Madison-No72 小时前
多语言聊天大模型--测试报告
linux·git·python·selenium·jmeter·自动化·postman
Liuqy-052 小时前
特殊进程——孤儿、僵尸、守护进程
linux·运维·服务器
流浪0012 小时前
Linux系统篇47——线程(十二) POSIX 信号量与环形队列,把判空判满提前到访问之前
linux·操作系统·线程·信号量·环形队列
咖丨喱2 小时前
【MMC Core + hc16 Host(WiFi SDIO 如何落到控制器)】
linux
等我调个Bug2 小时前
【Linux系统篇】权限
linux·服务器
~光~~3 小时前
【嵌入式linux学习】Cache 策略:Write-Through / Write-Back + Allocation
linux·学习·spring