accept()

PROTOTYPE

#include <sockets.h>

int accept(int socket, void *addr, socklen_t *addrlen);

DESCRIPTION

accept() retrieves a connected TCP socket from a server socket that has accepted a client connection request. socket is the handle of a socket allocated by socket(), given a local port number by bind(), and put into the listen state by listen(). If the listening socket has a connected socket queued, accept() dequeues it and returns its handle.

Otherwise, accept() blocks until the next client-server connection is made if the listening socket is blocking, or sets errno to EWOULDBLOCK and returns -1 if it is non-blocking. Sockets are blocking by default but can be made non-blocking via ioctlsocket().

If addr is non-NULL, on successful return an address structure containing the connection’s remote address is written to *addr, either type sockaddr_in or sockaddr_in6 according to the connection type. The IP address and port number are written in network byte order.

On input, *addrlen is the size of the buffer referenced by addr. As output, it is the actual structure size, either sizeof(struct sockaddr_in) or sizeof(struct sockaddr_in6). If the buffer size is less than the structure size, the output is truncated to fit the buffer size.

If successful, accept() returns the handle of a connected TCP socket. The new socket inherits all the properties of the listening socket it was queued at. If an error occurs, it sets errno and returns -1.

ERROR CODES

EFAULT addr is not NULL and either addrlen is NULL or *addrlen less than 0.
EINVAL The socket is not in the listen state.
EMFILE Unable to allocate a socket descriptor, all sockets in use.
ENETDOWN TargetTCP has not been initialized.
ENOBUFS No buffer space is available.
ENOTSOCK socket is not a valid socket handle.
EOPNOTSUPP The socket type is not SOCK_STREAM.
EWOULDBLOCK The socket is non-blocking and no connection request is queued.

EXAMPLE

  int psock, sock;

   ...

    /*-----------------------------------------------------------------*/
    /* Wait for a client connection request.                           */
    /*-----------------------------------------------------------------*/
    sock = accept(psock, NULL, NULL);
    if (sock == -1)
    {
      perror("accept() failed");
      taskSleep(OsTicksPerSec);
      continue;
    }