深入探索 Linux listen() 函数 backlog 的含义
1:listen()回顾以及问题引入
2:正确的解释
3:实验验证
1:listen()回顾以及问题引入
listen()函数是网络编程中用来使服务器端开始监听端口的系统调用,首先来回顾下listen()函数的定义:
有关于第二个参数含义的问题网上有好几种说法,我总结了下主要有这么3种:
- Kernel会为
LISTEN状态的socket维护一个队列,其中存放SYN RECEIVED和ESTABLISHED状态的套接字,backlog就是这个队列的大小。 - Kernel会为
LISTEN状态的socket维护两个队列,一个是SYN RECEIVED状态,另一个是ESTABLISHED状态,而backlog就是这两个队列的大小之和。 - 第三种和第二种模型一样,但是
backlog是队列ESTABLISHED的长度。
有关上面说的两个状态SYN RECEIVED状态和ESTABLISHED状态,是TCP三次握手过程中的状态转化,具体可以参考下面的图(在新窗口打开图片):
2:正确的解释
那上面三种说法到底哪个是正确的呢?我下面的说法翻译自这个链接:
http://veithen.github.io/2014/01/01/how-tcp-backlog-works-in-linux.html
下面我翻译下作者的文章:
When an application puts a socket into LISTEN state using the listen syscall, it needs to specify a backlog for that socket. The backlog is usually described as the limit for the queue of incoming connections.
当一个应用使用listen系统调用让socket进入LISTEN状态时,它需要为该套接字指定一个backlog。backlog通常被描述为连接队列的限制。
Because of the 3-way handshake used by TCP, an incoming connection goes through an intermediate state SYN RECEIVED before it reaches the ESTABLISHED state and can be returned by the accept syscall to the application (see the part of the TCP state diagram reproduced above). This means that a TCP/IP stack has two options to implement the backlog queue for a socket in LISTEN state:
由于TCP使用的3次握手,连接在到达ESTABLISHED状态之前经历中间状态SYN RECEIVED,并且可以由accept系统调用返回到应用程序。这意味着TCP / IP堆栈有两个选择来为LISTEN状态的套接字实现backlog队列:
(备注:一种就是两种状态在一个队列,一种是分别在一个队列)
1 : The implementation uses a single queue, the size of which is determined by the backlog argument of the listen syscall. When a SYN packet is received, it sends back a SYN/ACK packet and adds the connection to the queue. When the corresponding ACK is received, the connection changes its state to ESTABLISHED and becomes eligible for handover to the application. This means that the queue can contain connections in two different state: SYN RECEIVED and ESTABLISHED. Only connections in the latter state can be returned to the application by the accept syscall.
1:使用单个队列实现,其大小由listen syscall的backlog参数确定。 当收到SYN数据包时,它发送回SYN/ACK数据包,并将连接添加到队列。 当接收到相应的ACK时,连接将其状态改变为已建立。 这意味着队列可以包含两种不同状态的连接:SYN RECEIVED和ESTABLISHED。 只有处于后一状态的连接才能通过accept syscall返回给应用程序。
2 : The implementation uses two queues, a SYN queue (or incomplete connection queue) and an accept queue (or complete connection queue). Connections in state SYN RECEIVED are added to the SYN queue and later moved to the accept queue when their state changes to ESTABLISHED, i.e. when the ACK packet in the 3-way handshake is received. As the name implies, the accept call is then implemented simply to consume connections from the accept queue. In this case, the backlog argument of the listen syscall determines the size of the accept queue.
2 : 使用两个队列实现,一个SYN队列(或半连接队列)和一个accept队列(或完整的连接队列)。 处于SYN RECEIVED状态的连接被添加到SYN队列,并且当它们的状态改变为ESTABLISHED时,即当接收到3次握手中的ACK分组时,将它们移动到accept队列。 显而易见,accept系统调用只是简单地从完成队列中取出连接。 在这种情况下,listen syscall的backlog参数表示完成队列的大小。
Historically, BSD derived TCP implementations use the first approach. That choice implies that when the maximum backlog is reached, the system will no longer send back SYN/ACK packets in response to SYN packets. Usually the TCP implementation will simply drop the SYN packet (instead of responding with a RST packet) so that the client will retry.
历史上,BSD 派生系统实现的TCP使用第一种方法。 该选择意味着当达到最大backlog时,系统将不再响应于SYN分组发送回SYN/ACK分组。 通常,TCP的实现将简单地丢弃SYN分组,使得客户端重试。
On Linux, things are different, as mentioned in the man page of the listen syscall:
The behavior of the backlog argument on TCP sockets changed with Linux 2.2. Now it specifies the queue length for completely established sockets waiting to be accepted, instead of the number of incomplete connection requests. The maximum length of the queue for incomplete sockets can be set using /proc/sys/net/ipv4/tcp_max_syn_backlog.
在Linux上,是和上面不同的。如在listen系统调用的手册中所提到的:
在Linux内核2.2之后,socket backlog参数的形为改变了,现在它指等待accept的完全建立的套接字的队列长度,而不是不完全连接请求的数量。 不完全连接的长度可以使用/proc/sys/net/ipv4/tcp_max_syn_backlog设置。
This means that current Linux versions use the second option with two distinct queues: a SYN queue with a size specified by a system wide setting and an accept queue with a size specified by the application.
这意味着当前Linux版本使用上面第二种说法,有两个队列:具有由系统范围设置指定的大小的SYN队列 和 应用程序(也就是backlog参数)指定的accept队列。
OK,说到这里,相信backlog含义已经解释的非常清楚了,下面我们用实验验证下这种说法:
3:实验验证
验证环境:
RedHat 7
Linux version 3.10.0-514.el7.x86_64
验证思路:
1:客户端开多个线程分别创建socket去连接服务端。
2:服务端在listen之后,不去调用accept,也就是不会从已完成队列中取走socket连接。
3:观察结果,到底服务端会怎么样?处于ESTABLISHED状态的套接字个数是不是就是backlog参数指定的大小呢?
我们定义backlog的大小为5:
# define BACKLOG 5
看下我系统上默认的SYN队列大小:
也就是我现在两个队列的大小分别是 :
SYN队列大小:256
ACCEPT队列大小:5
看看我们的服务端程序 server.c :
#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<sys/time.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<errno.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#define PORT 8888 //端口号
#define BACKLOG 5 //BACKLOG大小
void my_err(const char* msg,int line)
{
fprintf(stderr,"line:%d",line);
perror(msg);
}
int main(int argc,char *argv[])
{
int conn_len;
int sock_fd,conn_fd;
struct sockaddr_in serv_addr,conn_addr;
if((sock_fd = socket(AF_INET,SOCK_STREAM,0)) == -1) {
my_err("socket",__LINE__);
exit(1);
}
memset(&serv_addr,0,sizeof(struct sockaddr_in));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
if(bind(sock_fd,(struct sockaddr *)&serv_addr,sizeof(struct sockaddr_in)) == -1) {
my_err("bind",__LINE__);
exit(1);
}
if(listen(sock_fd,BACKLOG) == -1) {
my_err("sock",__LINE__);
exit(1);
}
conn_len = sizeof(struct sockaddr_in);
sleep(10); //sleep 10s之后接受一个连接
printf("I will accept one\n");
accept(sock_fd,(struct sockaddr *)&conn_addr,(socklen_t *)&conn_len);
sleep(10); //同理,再接受一个
printf("I will accept one\n");
accept(sock_fd,(struct sockaddr *)&conn_addr,(socklen_t *)&conn_len);
sleep(10); //同理,再次接受一个
printf("I will accept one\n");
accept(sock_fd,(struct sockaddr *)&conn_addr,(socklen_t *)&conn_len);
while(1) {} //之后进入while循环,不释放连接
return 0;
}
客户端程序 client.c:
#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<string.h>
#include<strings.h>
#include<stdlib.h>
#include<unistd.h>
#include<pthread.h>
#define PORT 8888
#define thread_num 10 //定义创建的线程数量
struct sockaddr_in serv_addr;
void *func()
{
int conn_fd;
conn_fd = socket(AF_INET,SOCK_STREAM,0);
printf("conn_fd : %d\n",conn_fd);
if( connect(conn_fd,(struct sockaddr *)&serv_addr,sizeof(struct sockaddr_in)) == -1) {
printf("connect error\n");
}
while(1) {}
}
int main(int argc,char *argv[])
{
memset(&serv_addr,0,sizeof(struct sockaddr_in));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
inet_aton("192.168.30.155",(struct in_addr *)&serv_addr.sin_addr); //此IP是局域网中的另一台主机
int retval;
//创建线程并且等待线程完成
pthread_t pid[thread_num];
for(int i = 0 ; i < thread_num; ++i)
{
pthread_create(&pid[i],NULL,&func,NULL);
}
for(int i = 0 ; i < thread_num; ++i)
{
pthread_join(pid[i],(void*)&retval);
}
return 0;
}
编译运行程序,并用netstat命令监控服务端8888端口的情况:
$ gcc server.c -o server
$ gcc client.c -o client -lpthread -std=c99
# watch -n 1 “netstat -natp | grep 8888” //root执行
//watch -n 1 表示每秒显示一次引号中命令的结果
//netstatn: 以数字化显示 a:all t:tcp p:显示pid和进程名字然后我们grep端口号8888就行了。$ ./server
$ ./client
结果如下:
首先是watch的情况:
- 因为我们客户端用10个线程去连接服务器,因此服务器上有10条连接。
- 第一行的
./server状态是LISTEN,这是服务器进程。 - 倒数第三行的
./server是服务器已经执行了一次accept。 - 6条
ESTABLISHED状态比我们的BACKLOG参数5大1。 - 剩余的
SYN_RECV状态即使收到了客户端第三次握手回应的ACK也不能成为ESTABLISHED状态,因为BACKLOG队列中没有位置。
然后过了10s左右,等到服务器执行了第二个accept之后,服务器情况如下,它执行了第二个accept:
此时watch监控的画面如下:
- 和上面相比,服务器再次
accept之后,多了一条./server的连接。 - 有一条连接从
SYN_RECV状态转换到了ESTABLISHED状态,原因是accept函数从BACKlOG完成的队列中取出了一个连接,接着有空间之后,SYN队列的一个链接就可以转换成ESTABLISHED状态然后放入BACKlOG完成队列了。
好了,分析到这里,有关BACKLOG的问题已经解决了,至于继续上面的实验将backlog的参数调大会怎么样呢?我试过了,就是ESTABLISHED状态的数量也会增大,值会是BACKLOG+1,至于为什么是BACKLOG+1呢???我也没有搞懂。欢迎指教。
当然,还有别的有意思的问题是 : 如果ESTABLISHED队列满了,可是有连接需要从SYN队列转移过来时会发生什么?
一边在喊:让我过来!我满足条件了。
一边淡淡的说:过个毛啊,没看没地方‘ 住 ‘ 吗?~
改天再细说吧,欢迎评论交流~
深入探索 Linux listen() 函数 backlog 的含义的更多相关文章
- listen()函数中backlog参数分析
实例分析1 将服务器端的listen函数backlog设置为2,用20个客户端与服务器建立连接,查看连接的建立情况. 服务器代码: #include <stdio.h> #include& ...
- linux tcp listen函数的参数backlog
1 listen函数(http://man7.org/linux/man-pages/man2/listen.2.html) int listen(int sockfd, int backlog); ...
- tcp/ip协议listen函数中backlog參数的含义
listen函数的定义例如以下所看到的: #include <sys/socket.h> int accept(int sockfd, struct sockaddr * restrict ...
- 曹工说Redis源码(4)-- 通过redis server源码来理解 listen 函数中的 backlog 参数
文章导航 Redis源码系列的初衷,是帮助我们更好地理解Redis,更懂Redis,而怎么才能懂,光看是不够的,建议跟着下面的这一篇,把环境搭建起来,后续可以自己阅读源码,或者跟着我这边一起阅读.由于 ...
- socket编程listen函数限制连接数的解决方案
函数原型: int listen(int sockfd, int backlog); 当服务器编程时,经常需要限制客户端的连接个数,下面为问题分析以及解决办法: 下面只讨论TCP UDP不做讨论(很 ...
- listen函数
listen函数仅仅由TCP服务器调用,它做2件事: 1)当socket函数创建一个套接字时,它被假设为一个主动套接字,也就是说,它是一个将调用connect发起连接的客户套接字 listen函数把一 ...
- 网络编程socket之listen函数
摘要:listen函数使用主动连接套接口变为被连接套接口,使得一个进程可以接受其它进程的请求,从而成为一个服务器进程.在TCP服务器编程中listen函数把进程变为一个服务器,并指定相应的套接字变为被 ...
- 探索C++虚函数在g++中的实现
本文是我在追查一个诡异core问题的过程中收获的一点心得,把公司项目相关的背景和特定条件去掉后,仅取其中通用的C++虚函数实现部分知识记录于此. 在开始之前,原谅我先借用一张图黑一下C++: “无敌” ...
- listen() 函数
声明:本文来自网络博文的合并,文后有链接. 一.listen函数仅由TCP服务器调用 它做两件事: 1.当socket函数创建一个套接字时,它被假设为一个主动套接字,也就是说,它是一个将调用conne ...
随机推荐
- 配置阿里云gradle
build.gradle buildscript { ext { springBootVersion = '1.5.15.BUILD-SNAPSHOT' } repositories { // mav ...
- django 对models中上传的文件或图片改名
def user_directory_path(instance,filename): print instance,filename ext = filename.split('.')[-1] pr ...
- 🧚♂️全套Java教程_Java基础入门教程,零基础小白自学Java必备教程👨💻004 # 第四单元 流程控制语句上 #
一.本单元知识点概述 二.本单元目标 (Ⅰ)重点知识目标 1.if语句的格式及执行流程2.switch语句的格式及执行流程 (Ⅱ)能力目标 1.掌握if语句的格式及执行流程2.掌握switch语句的格 ...
- openEuler 20.03/21.03 - 华为欧拉开源版(CentOS 8 华为版开源版)下载
开始 openEuler 之旅吧 openEuler 通过社区合作,打造创新平台,构建支持多处理架构.统一和开放的操作系统,推动软硬件应用生态繁荣发展. 好玩的活动停不下来 openEuler 社区不 ...
- Python代码阅读(第10篇):随机打乱列表元素
本篇阅读的代码实现了随机打乱列表元素的功能,将原有列表乱序排列,并返回一个新的列表(不改变原有列表的顺序). 本篇阅读的代码片段来自于30-seconds-of-python. shuffle fro ...
- CF1082G Petya and Graph(最小割,最大权闭合子图)
QWQ嘤嘤嘤 感觉是最水的一道\(G\)题了 顺便记录一下第一次在考场上做出来G qwqqq 题目大意就是说: 给你n个点,m条边,让你选出来一些边,最大化边权减点权 \(n\le 1000\) QW ...
- SpringBoot使用注解进行分页
分页使用可以说非常普遍了,有时候会需要非常灵活的方式去开启或关闭分页,尝试使用一下注解的方式来进行分页. 依赖安装 需要使用的依赖: Mybatis-Plus PageHelper SpringBoo ...
- 某个buuctf的题(easy_tornado)
题目:http://88099f53-12b6-470a-9993-b73e4155940e.node3.buuoj.cn/ 1首先看三个文件的内容 2简单分析 如果出题人没整一些花里胡哨的,那么fl ...
- 实用 | 利用 aardio 配合 Python 快速开发桌面应用
1. 前言 大家好,我是安果! 我们都知道 Python 可以用来开发桌面应用,一旦功能开发完成,最后打包的可执行文件体积大,并且使用 Python 开发桌面应用周期相对较长 假如想快速开发一款 PC ...
- 你对微信小程序的理解?优缺点?
一.是什么 2017年,微信正式推出了小程序,允许外部开发者在微信内部运行自己的代码,开展业务 截至目前,小程序已经成为国内前端的一个重要业务,跟 Web 和手机 App 有着同等的重要性 小程序是一 ...