0

I created simple server.py that listen connection, but not accept connection.

import socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
PORT = 1234
server_socket.bind(("", PORT))
server_socket.listen(5)

while 1:
        pass

server_socket.close()
                             

When I run this code,

  • nc client could connect to the server
  • server created ESTABLISHED socket for the client
    netstat -an | grep 1234
    tcp        0      0 0.0.0.0:1234            0.0.0.0:*               LISTEN     
    tcp        0      0 3.3.3.3:1234      4.4.4.4:51493     ESTABLISHED
    tcp        0      0 3.3.3.3:1234      4.4.4.4:51494     ESTABLISHED
    

Question:
As far as I know, listen just gather connection in backlog queue, and then accept creates ESTABLISHED socket.
However the result: listen itself creates socket.

I also checked source code but could not find the socket creation code.
Can anyone knows the reason why this happens?

Jiwon
  • 1,074
  • 1
  • 11
  • 27

1 Answers1

0

As far as I know, listen just gather connection in backlog queue, and then accept creates ESTABLISHED socket.

This is wrong. listen tells the OS to accept new connections. accept then gets the inside the OS already established connections into the application. The backlog parameter for listen defines roughly how many connections can be accepted by the OS before they application needs to retrieve these using accept.

Therefore, the OS will accept new connections as long as listen was called, even before accept is called.

Steffen Ullrich
  • 114,247
  • 10
  • 131
  • 172