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這個面向無連接的強大的協議,開新貼去了解網絡層具體干了哪些事。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM