3

ret = listen(connection_socket, 1); //allowing one connection in queue

I have opened 2 terminals and ran client process in all 2 terminals at the same time.

Here server is busy in processing client1 data, now client2 is in pending queue. Now queue is full.

At this stage, i have launched 3rd terminal and ran client process. Sine queue is full, connect for this client should return -1 and errno should set to ECONNREFUSED, but in this case, connect is returning 0 for client 3 too. Then what is the purpose of listen() system call.

Abhishek Sagar
  • 1,189
  • 4
  • 20
  • 44
  • 1
    It seems the "or" clause of the [`listen` documentation](http://man7.org/linux/man-pages/man2/listen.2.html) may provide the hint you're looking for. – WhozCraig Feb 12 '20 at 04:34

1 Answers1

9

listen tells the TCP/IP stack to start accept incoming TCP connections on the port the socket is binded to.

The backlog parameter is not a "maximum number of connections allowed" parameter. Rather it's just a hint to the stack about how many TCP connections can be accepted on the socket's port before the applicaiton code has invoked accept on that socket. Be aware that accept doesn't negotiate a TCP handshake, it just takes one of the already accepted connections out of the backlog queue (or waits for one to arrive).

So if your backlog is 1 and your server thread isn't waiting on accept, than means that an incoming client connection will at least establish the TCP handshake. If you attempt to have two pending connections when the backlog queue is 1, the second client connection will likely timeout or be refused if the server code isn't actively invoking accept to promote those connections out of the backlog and into sockets.

selbie
  • 100,020
  • 15
  • 103
  • 173