1:listen()回顾以及问题引入
2:正确的解释
3:实验验证

1:listen()回顾以及问题引入

listen()函数是网络编程中用来使服务器端开始监听端口的系统调用,首先来回顾下listen()函数的定义:

有关于第二个参数含义的问题网上有好几种说法,我总结了下主要有这么3种:

  1. Kernel会为LISTEN状态的socket维护一个队列,其中存放SYN RECEIVEDESTABLISHED状态的套接字,backlog就是这个队列的大小。
  2. Kernel会为LISTEN状态的socket维护两个队列,一个是SYN RECEIVED状态,另一个是ESTABLISHED状态,而backlog就是这两个队列的大小之和。
  3. 第三种和第二种模型一样,但是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状态时,它需要为该套接字指定一个backlogbacklog通常被描述为连接队列的限制。

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 syscallbacklog参数确定。 当收到SYN数据包时,它发送回SYN/ACK数据包,并将连接添加到队列。 当接收到相应的ACK时,连接将其状态改变为已建立。 这意味着队列可以包含两种不同状态的连接:SYN RECEIVEDESTABLISHED。 只有处于后一状态的连接才能通过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 表示每秒显示一次引号中命令的结果
//netstat n: 以数字化显示 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 的含义的更多相关文章

  1. listen()函数中backlog参数分析

    实例分析1 将服务器端的listen函数backlog设置为2,用20个客户端与服务器建立连接,查看连接的建立情况. 服务器代码: #include <stdio.h> #include& ...

  2. linux tcp listen函数的参数backlog

    1 listen函数(http://man7.org/linux/man-pages/man2/listen.2.html) int listen(int sockfd, int backlog); ...

  3. tcp/ip协议listen函数中backlog參数的含义

    listen函数的定义例如以下所看到的: #include <sys/socket.h> int accept(int sockfd, struct sockaddr * restrict ...

  4. 曹工说Redis源码(4)-- 通过redis server源码来理解 listen 函数中的 backlog 参数

    文章导航 Redis源码系列的初衷,是帮助我们更好地理解Redis,更懂Redis,而怎么才能懂,光看是不够的,建议跟着下面的这一篇,把环境搭建起来,后续可以自己阅读源码,或者跟着我这边一起阅读.由于 ...

  5. socket编程listen函数限制连接数的解决方案

    函数原型: int listen(int sockfd, int backlog); 当服务器编程时,经常需要限制客户端的连接个数,下面为问题分析以及解决办法: 下面只讨论TCP  UDP不做讨论(很 ...

  6. listen函数

    listen函数仅仅由TCP服务器调用,它做2件事: 1)当socket函数创建一个套接字时,它被假设为一个主动套接字,也就是说,它是一个将调用connect发起连接的客户套接字 listen函数把一 ...

  7. 网络编程socket之listen函数

    摘要:listen函数使用主动连接套接口变为被连接套接口,使得一个进程可以接受其它进程的请求,从而成为一个服务器进程.在TCP服务器编程中listen函数把进程变为一个服务器,并指定相应的套接字变为被 ...

  8. 探索C++虚函数在g++中的实现

    本文是我在追查一个诡异core问题的过程中收获的一点心得,把公司项目相关的背景和特定条件去掉后,仅取其中通用的C++虚函数实现部分知识记录于此. 在开始之前,原谅我先借用一张图黑一下C++: “无敌” ...

  9. listen() 函数

    声明:本文来自网络博文的合并,文后有链接. 一.listen函数仅由TCP服务器调用 它做两件事: 1.当socket函数创建一个套接字时,它被假设为一个主动套接字,也就是说,它是一个将调用conne ...

随机推荐

  1. Feign超时不生效问题

    使用Feign作为RPC调用组件,可以配置连接超时和读取超时两个参数 使用Feign配置超时需要注意:Feign内部使用了负载均衡组件Ribbon,而Ribbon本身也有连接超时和读取超时相关配置一. ...

  2. Jmeter系列(27)- 常用逻辑控制器(6) | 如果(if)控制器If Controller

    如果(if)控制器(If Controller) 在实际工作中,当使用JMeter做性能脚本或者接口脚本时,当遇到需要对不同的条件做不同的操作时,我们可以使用JMeter中if控制器来实现 if控制器 ...

  3. Linux系列(21) - 光盘、U盘挂载

    挂载光盘 mount命令.umount命令 step-1 建立挂载点 原理:相当于建立盘符,建个目录读取光盘内容 命令:[root@localhost ~]# mkdir /mnt/cdrom/ 备注 ...

  4. javascript 无限分类

    * 根据php无限分类实现js版本的 /** * 根节点 parentid=0, 每个节点都有id, parentid字段 * @param items * @returns {*} */ funct ...

  5. Yaml书写方法详解

    一.关于yaml语法详解 yaml通常以空格做锁进,一般是2个或者4个,如果写更多,只要格式对其 就不会报错 二.yaml基本语法规则 大小写敏感 使用锁进表示层级关系 缩紧时候不允许用tab键,只能 ...

  6. python-matplotlib学习(1)

    1 import matplotlib.pyplot as plt 2 import numpy as np 3 4 x=np.linspace(-1,1,50) 5 y=2*x+1 6 plt.pl ...

  7. 位运算符的用法 ----非(!),与(&),或(|),异或(^)

    位运算符的用法 ----非(!),与(&),或(|),异或(^) 三种运算符均针对二进制 非!:是一元运算符.对一个二进制的整数按位取反,输入0则输出1,输入1则输出0. 例: 0100 -( ...

  8. 终端进程启动失败: shell 可执行文件“C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe”的路径不存在。

    因为某些原因重新安装1了vscode 和node  遇到了两个棘手的问题 ctrl + ~  打开终端提示 " 终端进程启动失败: shell 可执行文件"C:\Windows\S ...

  9. redux搭配react-redux进行跨组件通信开发

    Redux API 作用 createStore 用于创建一个store对象 bindActionCreators 用于简化操作,不用开发者手动触发dispatch React-redux API 作 ...

  10. Java集合——List,Set,Map总结笔记

    1. 集合 Collection 1.1 Java 集合框架 ​ ​ ​ ​ ​ ​ ​ ​ Java 集合框架位于 java.util 包中.Java 集合框架主要包括两种类型的容器,一种是集合(C ...