listen()
PROTOTYPE
#include <sockets.h>
int listen(int socket, int backlog);
DESCRIPTION
listen() is a non-blocking call that configures a TCP socket, bound to a local port and (optionally) IP address by bind(), to listen for connection requests. When the destination address of an incoming SYN matches the port number and - if not left as zero - IP address of a listening socket, it forks a child socket to complete the SYN-ACK handshake with the remote peer.
The child’s local IP address and port number are the destination IP address and port number of the connection request. Its remote address is the source address of the connection request. When the SYN-ACK handshake is finished, the connected child socket is queued on the listening socket.
socket is the listening socket’s handle. backlog is its maximum number of child sockets, both those performing the SYN-ACK handshake and those on its connected socket queue. Connection requests that arrive while the backlog is at its limit are ignored.
The number of child sockets is reduced by one each time an accept() call removes a connected socket from the listening socket’s queue. If a listening socket is closed, its current children are closed as well. That does not apply to connected sockets have been removed by accept().
If successful, listen() returns 0. Otherwise, it sets errno and returns -1.
ERROR CODES
| EINVAL | socket is not bound to a local port or backlog is not in [1,5]. |
| EISCONN | The socket is connected. |
| ENETDOWN | TargetTCP has not been initialized. |
| ENOTSOCK | socket is not a valid socket handle. |
| EOPNOTSUPP | The socket type is not SOCK_STREAM. |
EXAMPLE
/*-------------------------------------------------------------------*/
/* Put socket in listen state. */
/*-------------------------------------------------------------------*/
if (listen(psock, 5))
perror("listen() failed");