listen() — Prepare the server for incoming client requests

Standards

Standards / Extensions C or C++ Dependencies

XPG4.2
Single UNIX Specification, Version 3

both  

Format

X/Open:
#define _XOPEN_SOURCE_EXTENDED 1
#include <sys/socket.h>

int listen(int socket, int backlog);
Berkeley sockets:
#define _OE_SOCKETS
#include <sys/socket.h>

int listen(int socket, int backlog);

General description

The listen() function applies only to stream sockets. It indicates a readiness to accept client connection requests, and creates a connection request queue of length backlog to queue incoming connection requests. Once full, additional connection requests are rejected.
Parameter
Description
socket
The socket descriptor.
backlog
Defines the maximum length for the queue of pending connections.

The listen() call indicates a readiness to accept client connection requests. It transforms an active socket into a passive socket. Once called, socket can never be used as an active socket to initiate connection requests. Calling listen() is the third of four steps that a server performs to accept a connection. It is called after allocating a stream socket with socket(), and after binding a name to socket with bind(). It must be called before calling accept().

If the backlog is less than 0, backlog is set to 0. If the backlog is greater than SOMAXCONN, as defined in sys/socket.h, backlog is set to SOMAXCONN.

For AF_UNIX sockets, this value is variable and can be set in the application. For AF_INET and AF_INET6 sockets, the value cannot exceed the maximum number of connections allowed by the installed TCP/IP.

Special behavior for C++: To use this function with C++, you must use the _XOPEN_SOURCE_EXTENDED 1 feature test macro.

Returned value

If successful, listen() returns 0.

If unsuccessful, listen() returns -1 and sets errno to one of the following values:
Error Code
Description
EBADF
The socket parameter is not a valid socket descriptor.
EDESTADDRREQ
The socket is not bound to a local address, and the protocol does not support listening on an unbound socket.
EINVAL
An invalid argument was supplied. The socket is not named (a bind() has not been done), or the socket is ready to accept connections (a listen() has already been done). The socket is already connected.
ENOBUFS
Insufficient system resources are available to complete the call.
ENOTSOCK
The descriptor is for a file, not for a socket.
EOPNOTSUPP
The socket parameter is not a socket descriptor that supports the listen() call.

Related information