Skip to content

accept()

Purpose

accept() accepts a pending incoming connection and returns a new connected socket fd.

The listening socket remains open for future connections.

#include <sys/types.h>
#include <sys/socket.h>

Prototype

int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);

Minimal Example

struct sockaddr_in peer;
socklen_t peer_len = sizeof(peer);

int client_fd = accept(server_fd, (struct sockaddr *)&peer, &peer_len);
if (client_fd < 0) {
    perror("accept");
    return -1;
}

Common Pitfalls

  • Forgetting to set the accepted client socket to non-blocking mode.
  • Not handling EAGAIN when the listening socket is non-blocking.
  • Confusing the listening socket with the connected client socket.