What happens when we say “listen to a port”?

前端 未结 4 2014
感情败类
感情败类 2021-02-01 04:48

When we start a server application, we always need to speicify the port number it listens to. But how is this \"listening mechanism\" implemented under the hood?

My cur

4条回答
  •  眼角桃花
    2021-02-01 05:19

    What happens when we say "listen to a port"?

    The typical TCP server sequence of calls is

    socket() -> bind()-> listen() -> accept() -> read()/write() -> close()
    

    A socket created by socket function is assumed to be an active socket (that will issue a connect()). listen() function converts unconnected socket to passive socket. This means that kernel should start accepting incoming connection requests. The second argument to listen() function specifies the total queue length for a given listening socket of 2 queues - (1) complete connection queue - 3 way handshake completed for connection (2) incomplete connection queue - SYN received from client waiting for completion of 3 way TCP handshake

    Finally accept() is called by TCP server to return the next completed connection from the front of completed connection queue. If accept() is successful it returns a new socket descriptor that refers to the TCP connection between client and server.

    Now to answer your question * The networking stack in the operating system kernel, reads each incoming IP packet, classifies the packet according to it's TCP/IP header fields. The arrival of IP packet on wire is serviced as an interrupt by an Ethernet driver and from there onwards kernel mode TCP/IP stack takes over

    • With respect to data if you mean the SYN packet, Posix.1g has an option to either ignore the new incoming SYN or send a RST to the client when the connection queue is full. Data that arrives after 3 way handshake completes, but before server calls accept should be queued by server TCP up to the size of connected socket's receive buffer.

    • listen() operation is a blocking call and returns after the connection state is said to passive to allow incoming TCP client connections.

    Refer to Wikipedia for more details on TCP protocol -handshake, sequencing and acknowledgments for reliable transmission.

    This book gives a very good details on TCP/IP Unix network programming and can provide more insight on this topic.

提交回复
热议问题