Search code examples
pythonsocketstcptcpserver

Delay accept() in Python socket connection


Using Sockets in Python3, can I:

  • listen() on a socket
  • when I receive a connection on that socket: connect() to another server
  • If the connection is successful, accept() the first connection, else close the socket

Is this possible? And if so, how?


Solution

  • accept is the way for the server application to know both that some client has connected and to get a socket to this client. But accept does not actually create the connection to the client. This connection will already be established by the OS just because the server socket was changed to the listen state. accept only provides the already established TCP connection to the application.

    So you need to actually call accept first to even know that there is some client connecting to the server. If you don't want this client just close the accepted connection.

    Note that some OS have the concept of accept filters, where connections can be checked inside the kernel before they are returned by accept. But even in this case the TCP connection is first established, and from the perspective of the client there is not much of a difference where the established connection is actually closed, i.e. OS kernel or server application.