How does the accept() function work?


I have a question about the accept() function in C.

When a server receive a connection, the accept() function creates a new socket to communicate with the client, and then let the "old socket" listening for new connections.

Then, I understand that the server can communicate with the client through the "new socket", but how can the client communicate with the "new socket" (because the client don't know about this "new socket") ?

Show source
| C   | server   | sockets   2017-01-06 20:01 4 Answers

Answers to How does the accept() function work? ( 4 )

  1. 2017-01-06 20:01

    Sockets are an abstraction of the network programming API. On the wire and for the client there is still only a single connection and the client does not see if the server is using a network API with listen, accept etc or if the server is using some other API or raw sockets to establish the connection.

  2. 2017-01-06 20:01

    On the server side, the listening socket is associated with only a local IP and port and is in the LISTEN state.

    In contrast, accepted sockets on the server (as well as connected sockets on the client) are identified by a local IP and port as well as a remote IP and port and is in the ESTABLISHED state.

    On the client side, it doesn't matter that the server uses a listening socket separate from the connected socket. By the time the client returns from connect, the server has returned from accept and the socket descriptors returned from each can communicate with each other.

  3. 2017-01-06 20:01

    The explanation is that a TCP (an end point in a TCP/IP transmission) is uniquely identified by the couple IPaddress/port_number. When a client asks for a connection, it does it using its IP and port number, a pair which is unique. That operation binds SRCIP+SRCPORT to DSTIP+DSTPORT, and those 4 numbers (the two IPs plus the two ports) uniquely identify a connection. So the two sockets on the server really refer to two different connections/streams.

  4. 2017-01-06 20:01

    Any communication in IP protocol (including TCP/IP) occurs between two endpoints. The endpoints are always host:port. In the TCP world, the two endpoints identify the connection. A socket is associated with a connection, not with an endpoint.

    Thus, you can have 2 sockets returned from 2 accept() calls, describing 2 distinct connections.

    Here is an example of netstat -an output on a unix machine:

    tcp        0      0        *                   LISTEN
    tcp        0      0           ESTABLISHED
    tcp        0      0           ESTABLISHED
    tcp        0      0           ESTABLISHED
    tcp        0      0           ESTABLISHED
    tcp        0      0           ESTABLISHED
    tcp        0      0           ESTABLISHED

    Here we have a listening socket, and a few connections (each backed by its own socket) resulting from accept() on that socket.

Leave a reply to - How does the accept() function work?

◀ Go back