socket中的listen到底干了哪些事情?

创建一个套接字的时候,该套接字可以有两种状态,一个主动套接字(主动去连接),一个是被动套接字(等待连接)。

主动连接的理解起来,应该没什么问题,但是被动的呢?是在一直轮询还是一种中断?

在《卷1:套接字编程API》中并没有提到这个。

listen()主要做了以下:

1.维护了两个队列,已完成连接的队列和未完成链接的队列。之和不超过backlog的数值。

2.维护链接的时间RTT。中值为178ms。

3.在完成三次握手之后,在调用accept之前应该由服务器组织一个队列来排队。这个队列和backlog相关,队列容量=backlog*模糊因子,队列容量应该大于backlog

4.accept()函数不参与三次握手,而只负责从建立连接队列中取出一个连接和socketfd进行绑定

6.accept()函数调用,会从已连接队列中取出一个“连接”,未完成队列和已完成队列中连接目之和将减少1;即accept将监听套接字对应的sock的接收队列中的已建立连接的sk_buff取下(从该sk_buff中可以获得对端主机的发送过来的tcp/ip数据包)

7. 监听套接字的已完成队列中的元素个数大于0,那么该套接字是可读的。

8.当程序调用accept的时候(设置阻塞参数),那么判定该套接字是否可读,不可读则进入睡眠,直至已完成队列中的元素个数大于0(监听套接字可读)而唤起监听进程)。

9.isten函数一般在调用bind之后-调用accept之前调用。

 

稍稍总结一段,扯了一大段废话。总结起来就是,listen函数主要的工作包括,设置socket和sock结构体的标记和状态,设置syn和已连接队列的上限。

下面贴一段listen源码解析:

static int sock_listen(int fd, int backlog)
{
    struct socket *sock;

    if (fd < 0 || fd >= NR_OPEN || current->files->fd[fd] == NULL)
        return(-EBADF);
    if (!(sock = sockfd_lookup(fd, NULL))) 
        return(-ENOTSOCK);

    if (sock->state != SS_UNCONNECTED) 
    {
        return(-EINVAL);
    }

    if (sock->ops && sock->ops->listen)
        sock->ops->listen(sock, backlog);
    // 设置socket的监听属性,accept函数时用到
    sock->flags |= SO_ACCEPTCON;
    return(0);
}
static int inet_listen(struct socket *sock, int backlog)
{
    struct sock *sk = (struct sock *) sock->data;
    // 如果没有绑定端口则绑定一个,并把sock加到sock_array中
    if(inet_autobind(sk)!=0)
        return -EAGAIN;

    /* We might as well re use these. */ 
    /*
     * note that the backlog is "unsigned char", so truncate it
     * somewhere. We might as well truncate it to what everybody
     * else does..
     */
    if ((unsigned) backlog > 128)
        backlog = 128;
    // 设置syn+已连接队列的最大长度,在tcp.c中用到
    sk->max_ack_backlog = backlog;
    // 防止多次调用listen
    if (sk->state != TCP_LISTEN)
    {   
        // syn+已连接队列长度
        sk->ack_backlog = 0;
        sk->state = TCP_LISTEN;
    }
    return(0);
}
// 绑定一个随机的端口,更新sk的源端口字段,并把sk挂载到端口对应的队列中
static int inet_autobind(struct sock *sk)
{
    // 已经绑定了端口则直接返回,否则获取一个随机的端口
    if (sk->num == 0) 
    {
        sk->num = get_new_socknum(sk->prot, 0);
        if (sk->num == 0) 
            return(-EAGAIN);
        put_sock(sk->num, sk);
        sk->dummy_th.source = ntohs(sk->num);
    }
    return 0;
}

  下面是man中解释:

LISTEN(2)                                         Linux Programmer's Manual                                        LISTEN(2)

NAME
       listen - listen for connections on a socket

SYNOPSIS
       #include <sys/types.h>          /* See NOTES */
       #include <sys/socket.h>

       int listen(int sockfd, int backlog);

DESCRIPTION
       listen() marks the socket referred to by sockfd as a passive socket, that is, as a socket that will be used to accept
       incoming connection requests using accept(2).

       The sockfd argument is a file descriptor that refers to a socket of type SOCK_STREAM or SOCK_SEQPACKET.

       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  con‐
       nection succeeds.

RETURN VALUE
       On success, zero is returned.  On error, -1 is returned, and errno is set appropriately.

ERRORS
       EADDRINUSE
              Another socket is already listening on the same port.

       EADDRINUSE
              (Internet  domain  sockets)  The socket referred to by sockfd had not previously been bound to an address and,
              upon attempting to bind it to an ephemeral port, it was determined that all port numbers in the ephemeral port
              range are currently in use.  See the discussion of /proc/sys/net/ipv4/ip_local_port_range in ip(7).

       EBADF  The argument sockfd is not a valid descriptor.

       ENOTSOCK
              The file descriptor sockfd does not refer to a socket.

       EOPNOTSUPP
              The socket is not of a type that supports the listen() operation.
RETURN VALUE
       On success, zero is returned.  On error, -1 is returned, and errno is set appropriately.

ERRORS
       EADDRINUSE
              Another socket is already listening on the same port.

       EADDRINUSE
              (Internet  domain  sockets)  The socket referred to by sockfd had not previously been bound to an address and,
              upon attempting to bind it to an ephemeral port, it was determined that all port numbers in the ephemeral port
              range are currently in use.  See the discussion of /proc/sys/net/ipv4/ip_local_port_range in ip(7).

       EBADF  The argument sockfd is not a valid descriptor.

       ENOTSOCK
              The file descriptor sockfd does not refer to a socket.

       EOPNOTSUPP
              The socket is not of a type that supports the listen() operation.

CONFORMING TO
       POSIX.1-2001, POSIX.1-2008, 4.4BSD (listen() first appeared in 4.2BSD).

NOTES
       To accept connections, the following steps are performed:

           1.  A socket is created with socket(2).

           2.  The socket is bound to a local address using bind(2), so that other sockets may be connect(2)ed to it.

           3.  A  willingness  to  accept incoming connections and a queue limit for incoming connections are specified with
               listen().

           4.  Connections are accepted with accept(2).

       POSIX.1 does not require the inclusion of <sys/types.h>, and this header file is not  required  on  Linux.   However,
       some  historical  (BSD)  implementations  required  this  header file, and portable applications are probably wise to
       include it.

       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.   When
       syncookies  are enabled there is no logical maximum length and this setting is ignored.  See tcp(7) for more informa‐
       tion.

       If the backlog argument is greater than the value in /proc/sys/net/core/somaxconn, then it is silently  truncated  to
       that  value;  the  default  value  in this file is 128.  In kernels before 2.4.25, this limit was a hard coded value,
       SOMAXCONN, with the value 128.

EXAMPLE
       See bind(2).

SEE ALSO
       accept(2), bind(2), connect(2), socket(2), socket(7)

COLOPHON
       This page is part of release 4.04 of the Linux man-pages project.  A description of the  project,  information  about
       reporting bugs, and the latest version of this page, can be found at http://www.kernel.org/doc/man-pages/.

Linux                                                    2015-12-28                                                LISTEN(2)

  

这个问题还是个迷,不过我已经有了一个好的解释,listen其实跟轮询还是中断压根没关系,这就是一个记录的作用,在内存中有一个队列维护网络连接罢了,看样网络链接来临时具体干大事的并不是listen()了,这个问题留到三次握手之前,我想这个链接的问题应该在ip层考虑,三次握手建立链接之后才有了应用层的事。而三次握手之前就是ip这个面向无连接的强大的协议,开新贴去了解网络层具体干了哪些事。

posted @ 2020-09-03 23:41  Smah  阅读(3026)  评论(0编辑  收藏  举报