SO_SNDBUF和SO_RCVBUF

                   这两个选项就是设置和获取缓冲区的大小,看代码吧。

发送缓冲区:

 

[mapan@localhost unixNetwork]$ cat test.cpp 
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include <malloc.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/ioctl.h>
#include <stdarg.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <signal.h>
#define MAXLINE 4096



int main()
{
   int listenfd,connfd;
   socklen_t  clilen;
   struct sockaddr_in cliaddr,servaddr;

   listenfd=socket(AF_INET,SOCK_STREAM,0);
   

   int buf_len;
   socklen_t len=sizeof(buf_len);
   getsockopt(listenfd,SOL_SOCKET,SO_SNDBUF,(void *)&buf_len,&len);
   printf("buf:%d\n",buf_len);

   int setbuf=80000;
   socklen_t len1=sizeof(setbuf);
   setsockopt(listenfd,SOL_SOCKET,SO_SNDBUF,(void *)&setbuf,len1);
 
   getsockopt(listenfd,SOL_SOCKET,SO_SNDBUF,(void *)&buf_len,&len);
   printf("buf:%d\n",buf_len);  


   getchar();
   close(listenfd);
   return 0;
}
[mapan@localhost unixNetwork]$ g++ test.cpp 
[mapan@localhost unixNetwork]$ ./a.out 
buf:16384
buf:160000

 

 

接收缓冲区:

 

[mapan@localhost unixNetwork]$ cat test.cpp 
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include <malloc.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/ioctl.h>
#include <stdarg.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <signal.h>
#define MAXLINE 4096



int main()
{
   int listenfd,connfd;
   socklen_t  clilen;
   struct sockaddr_in cliaddr,servaddr;

   listenfd=socket(AF_INET,SOCK_STREAM,0);
   

   int buf_len;
   socklen_t len=sizeof(buf_len);
   getsockopt(listenfd,SOL_SOCKET,SO_RCVBUF,(void *)&buf_len,&len);
   printf("buf:%d\n",buf_len);

   int setbuf=80000;
   socklen_t len1=sizeof(setbuf);
   setsockopt(listenfd,SOL_SOCKET,SO_RCVBUF,(void *)&setbuf,len1);
 
   getsockopt(listenfd,SOL_SOCKET,SO_RCVBUF,(void *)&buf_len,&len);
   printf("buf:%d\n",buf_len);  


   getchar();
   close(listenfd);
   return 0;
}
[mapan@localhost unixNetwork]$ g++ test.cpp 
[mapan@localhost unixNetwork]$ ./a.out 
buf:87380
buf:160000

 

 

前言万语不如代码来的实在,如果是服务端setsockopt要在listen函数之前调用,客户端则在connect函数之前调用,注意setsockopt和getsockopt最后一个参数有区别。这里还有一个小细节要说明一下:进程设置的SO_SNDBUF和SO_RCVBUF也并不是真正的上限,在内核中会把该值翻一倍作为缓存上限使用。

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

盼盼编程

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值