Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to deeply understand the listen implementation of TCP/IP protocol

Shulou Source: shulou.com Published: 2022-06-01 20:54:26 10月27日 Update

How to deeply understand the listen implementation of TCP/IP protocol? in view of this problem, this article introduces the corresponding analysis and answer in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible method.

The logic of the listen function is simpler than bind. Bind is mainly about checksum binding ip and port. Listen modifies the state of the socket and records some settings.

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)

/ / set the listening property of socket, which is used in the accept function.

Sock- > flags | = SO_ACCEPTCON

Return (0)

}

Static int inet_listen (struct socket * sock, int backlog)

{

Struct sock * sk = (struct sock *) sock- > data

/ / bind one if no port is bound, and add sock to sock_array

If (inet_autobind (sk)! = 0)

Return-EAGAIN

If ((unsigned) backlog > 128)

Backlog = 128,

/ / the upper limit of the length of the tcp receiving queue varies with system implementation. For more information, please see the use of tcp.c.

Sk- > max_ack_backlog = backlog

/ / modify socket status to prevent multiple calls to listen

If (sk- > state! = TCP_LISTEN)

{

Sk- > ack_backlog = 0

Sk- > state = TCP_LISTEN

}

Return (0)

}

/ / bind a random port, update the source port field of sk, and mount the sk to the queue corresponding to the port. See the analysis of bind function.

Static int inet_autobind (struct sock * sk)

{

/ * We may need to bind the socket. , /

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

}

This is the answer to the question on how to deeply understand the listen implementation of the TCP/IP protocol. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel to learn more about it.

Tags: Port function question more status queue analysis help solution different easy easy upper limit content field buddy partner property method knowledge Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Tech Info Docker Shulou Technology Xiaomi vpn