1. 背景:
面试偶尔会被问到backlog作用,之前只知道是监听队列的长度,本文先通过抓包了解listen的backlog。
2. 官方文档的解释:
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 backlog argument defines the maximum length to which the queue of pending connections for
sockfd may grow. If a connection request arrives when the queue is full, the client may
receive an error with an indication of ECONNREFUSED or, if the underlying protocol supports
retransmission, the request may be ignored so that a later reattempt at connection succeeds.
man listen出来的结果中显示,backlog在内核2.2版本之后,表示的是建立连接的队列长度,而不是之前版本中的不完全的连接(SYNC_RECV状态)。
如果队列满,则会尝试重传。
3. 现象:
服务端代码:服务端监听后不做任何接受操作。
#define CHECK(s) do { \
if ((s) == -1) { \
printf ("Internal error in %d\n", __LINE__); \
printf ("ERROR : %s\n", strerror (errno)); \
exit (1); \
} \
} while (0)
#define PORT 8888
int main ()
{
int fd;
struct sockaddr_in saddr;
fd = socket (AF_INET, SOCK_STREAM, 0);
CHECK (fd);
memset (&saddr, 0, sizeof (saddr));
saddr.sin_family = AF_INET;
saddr.sin_port = htons (PORT);
saddr.sin_addr.s_addr = htonl (INADDR_A