Skip to content
/linux-syscalls

Network · Section 2

accept(2)

Pull the next pending connection off a listening socket's queue.

Signature

#include <sys/socket.h>

int accept(int sockfd, struct sockaddr * addr, socklen_t * addrlen);
sockfd
Listening socket descriptor (previously listen()ed).
addr
If non-NULL, the kernel writes the peer's sockaddr here. Cast appropriately (sockaddr_in for INET, sockaddr_in6, sockaddr_un, …).
addrlen
Pointer to a socklen_t. In: size of the buffer. Out: size of the actual address (may be larger than the buffer — the address is truncated).

Description

accept() extracts the first pending connection from the queue of a listening socket and returns a new connected socket — a separate file descriptor that can be read/written like any other. The original listening sockfd is unchanged and continues to accept further connections. If the queue is empty and the socket is blocking, accept() blocks; if non-blocking it returns -1/EAGAIN. The peer address is written to *addr / *addrlen if non-NULL — addr can be NULL when you don't care. Prefer accept4() over accept() in new code: it lets you set SOCK_CLOEXEC and SOCK_NONBLOCK atomically at accept time, eliminating an fd-leak race window across execve().

accept vs accept4

accept4() is accept() with a fourth flags argument. With flags set to 0 the two calls behave identically. The two flags it accepts are set on the new connected socket, atomically, as part of the same syscall:

FlagEffect on the returned fdWhat it replaces
SOCK_NONBLOCKSets O_NONBLOCK on the new socket's open file descriptionfcntl(fd, F_SETFL, flags | O_NONBLOCK) after accept()
SOCK_CLOEXECSets FD_CLOEXEC on the new descriptorfcntl(fd, F_SETFD, FD_CLOEXEC) after accept()

SOCK_CLOEXEC is the one that matters for correctness. In a multithreaded program, the gap between accept() returning and a follow-up fcntl(F_SETFD) is a window in which another thread can fork() and execve() a child that inherits the client socket. accept4(..., SOCK_CLOEXEC) closes that window. SOCK_NONBLOCK only saves a syscall.

Two Linux details catch people porting from BSD:

  • On Linux the accepted socket does not inherit O_NONBLOCK (or O_ASYNC) from the listening socket. A non-blocking listener still hands you blocking client sockets unless you pass SOCK_NONBLOCK or set it yourself.
  • accept4() started as a Linux extension (Linux 2.6.28, glibc 2.10, needs _GNU_SOURCE) and was standardized in POSIX.1-2024. Most servers you will debug (nginx, anything written in Go) call accept4 directly, so strace -e trace=accept on them shows nothing: filter on -e trace=accept,accept4.

Minimal TCP accept loop in C

A blocking server that answers every connection on 127.0.0.1:8080 and keeps running through the errors that are transient by design:

#define _GNU_SOURCE
#include <arpa/inet.h>
#include <errno.h>
#include <netinet/in.h>
#include <stdio.h>
#include <sys/socket.h>
#include <unistd.h>

int main(void) {
    int lfd = socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
    if (lfd == -1) { perror("socket"); return 1; }

    int one = 1;
    setsockopt(lfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one);

    struct sockaddr_in sa = { .sin_family = AF_INET,
                              .sin_port = htons(8080),
                              .sin_addr.s_addr = htonl(INADDR_LOOPBACK) };
    if (bind(lfd, (struct sockaddr *)&sa, sizeof sa) == -1) { perror("bind"); return 1; }
    if (listen(lfd, SOMAXCONN) == -1) { perror("listen"); return 1; }

    for (;;) {
        struct sockaddr_storage peer;
        socklen_t len = sizeof peer;          /* in: buffer size, out: address size */
        int cfd = accept4(lfd, (struct sockaddr *)&peer, &len, SOCK_CLOEXEC);
        if (cfd == -1) {
            if (errno == EINTR || errno == ECONNABORTED)
                continue;                     /* transient: try again */
            perror("accept4");
            if (errno == EMFILE || errno == ENFILE)
                sleep(1);                     /* out of fds: back off, don't spin */
            continue;
        }

        char host[INET6_ADDRSTRLEN] = "?";
        if (peer.ss_family == AF_INET)
            inet_ntop(AF_INET, &((struct sockaddr_in *)&peer)->sin_addr, host, sizeof host);
        printf("connection from %s, addrlen=%u\n", host, (unsigned)len);

        const char msg[] = "hello\n";
        write(cfd, msg, sizeof msg - 1);
        close(cfd);
    }
}

Build it with gcc -Wall -O2 -o server server.c, run it under strace, and connect with curl http://127.0.0.1:8080/:

$ strace -yy -e trace=socket,bind,listen,accept4,write ./server
socket(AF_INET, SOCK_STREAM|SOCK_CLOEXEC, IPPROTO_IP) = 3<TCP:[4573239]>
bind(3<TCP:[4573239]>, {sa_family=AF_INET, sin_port=htons(8080), sin_addr=inet_addr("127.0.0.1")}, 16) = 0
listen(3<TCP:[127.0.0.1:8080]>, 4096)   = 0
accept4(3<TCP:[127.0.0.1:8080]>, {sa_family=AF_INET, sin_port=htons(39820), sin_addr=inet_addr("127.0.0.1")}, [128 => 16], SOCK_CLOEXEC) = 4<TCP:[127.0.0.1:8080->127.0.0.1:39820]>
write(4<TCP:[127.0.0.1:8080->127.0.0.1:39820]>, "hello\n", 6) = 6
accept4(3<TCP:[127.0.0.1:8080]>, 0x7ffe7e380f10, [128], SOCK_CLOEXEC) = ? ERESTARTSYS (To be restarted if SA_RESTART is set)
--- SIGTERM {si_signo=SIGTERM, si_code=SI_USER, si_pid=2714153, si_uid=1000} ---

The last accept4 is the server blocked in the queue when it was killed: ERESTARTSYS is kernel-internal and only ever appears in traces, never in your program's errno.

addr and addrlen: in and out

addrlen is a value-result argument. Before the call it must hold the size of the buffer addr points to; after a successful call it holds the size of the peer address the kernel actually had. strace prints both values as [in => out], which is the [128 => 16] above: a 128-byte sockaddr_storage went in, a 16-byte sockaddr_in came out.

  • Reuse a socklen_t across loop iterations without resetting it and the second call sees the previous output size as the buffer size. Reset len = sizeof peer on every iteration, as the loop above does.
  • If the buffer is too small the address is silently truncated and addrlen comes back larger than what you passed. Compare before trusting the address.
  • If you do not need the peer address, pass NULL, NULL for both. You can still get it later with getpeername().
  • On failure addrlen is left unchanged, and the struct is not written, which is why strace shows a raw pointer (0x7ffe7e380f10) instead of a decoded address on the interrupted call.

EAGAIN / EWOULDBLOCK with non-blocking listeners and epoll

With a listening socket created with SOCK_NONBLOCK, accept() returns -1 with EAGAIN (or EWOULDBLOCK, same value on Linux; POSIX allows either) when the queue is empty. That is not an error, it is the signal to go back to epoll_wait().

Readiness is a hint, not a promise: between epoll_wait() reporting EPOLLIN and your accept(), the pending connection can be reset by the client or taken by another thread or process sharing the listener. A blocking listener would then block inside accept() and stall your event loop, so listeners driven by select, poll or epoll should always be non-blocking. With edge-triggered epoll (EPOLLET) you must also drain the queue until EAGAIN, because you will not be woken again for connections that were already pending:

/* Called when epoll reports EPOLLIN on lfd (created with SOCK_NONBLOCK). */
static void drain_accept_queue(int epfd, int lfd) {
    for (;;) {
        int cfd = accept4(lfd, NULL, NULL, SOCK_NONBLOCK | SOCK_CLOEXEC);
        if (cfd == -1) {
            if (errno == EAGAIN || errno == EWOULDBLOCK)
                return;               /* queue empty: back to epoll_wait() */
            if (errno == EINTR || errno == ECONNABORTED)
                continue;             /* transient */
            perror("accept4");        /* EMFILE/ENFILE: see below */
            return;
        }
        struct epoll_event ev = { .events = EPOLLIN | EPOLLRDHUP, .data.fd = cfd };
        epoll_ctl(epfd, EPOLL_CTL_ADD, cfd, &ev);
    }
}

What that looks like with one client connecting:

epoll_wait(4, [{events=EPOLLIN, data=0x3}], 64, 2000) = 1
accept4(3, NULL, NULL, SOCK_CLOEXEC|SOCK_NONBLOCK) = 5
accept4(3, NULL, NULL, SOCK_CLOEXEC|SOCK_NONBLOCK) = -1 EAGAIN (Resource temporarily unavailable)

Which errors to retry

The accept(2) man page has a Linux-specific rule that most example code ignores: accept() passes already-pending network errors on the new connection back as its own return value. For TCP/IP those are ENETDOWN, EPROTO, ENOPROTOOPT, EHOSTDOWN, ENONET, EHOSTUNREACH, EOPNOTSUPP and ENETUNREACH, and the man page says to treat them like EAGAIN and retry. They describe one failed client, not a broken listener.

errnoMeaningWhat the loop should do
EAGAIN / EWOULDBLOCKNon-blocking listener, queue emptyReturn to epoll_wait() / poll()
EINTRA caught signal arrived before a connectionRetry (or use SA_RESTART)
ECONNABORTEDA queued connection was aborted before you accepted itRetry
EPROTO, ENETDOWN, EHOSTUNREACH, ...Pending network error on that one connection (Linux behavior)Retry
EMFILE / ENFILEPer-process / system-wide fd limit reachedBack off; the connection stays queued, so a level-triggered loop will spin at 100% CPU
ENOBUFS / ENOMEMSocket buffer memory limitsBack off and retry
EINVALSocket is not listening (missing listen()), or bad addrlen / flagsBug: fix the code
EBADF, ENOTSOCKNot an open fd, or not a socketBug: fix the code

EOPNOTSUPP is ambiguous: on a SOCK_DGRAM socket it means accept() makes no sense there (a bug), on a TCP listener it is one of the pending network errors above.

EMFILE deserves its own plan. The connection that triggered it is still in the queue, so the listener stays readable and a naive event loop retries forever. Common fixes are raising RLIMIT_NOFILE (ulimit -n, LimitNOFILE= in a systemd unit), pausing accepts on the listener for a short time, or keeping a spare fd open (for example on /dev/null) that you close to accept and immediately close the excess connection.

Debugging a server's accept path with strace

  • Is the server even accepting? strace -f -p "$(pidof myserver)" -e trace=accept,accept4,epoll_wait,poll shows whether it is parked in epoll_wait with no events (nothing is connecting: check the bind address, firewall, ss -ltn) or calling accept4 and getting errors.
  • Stuck under load with full CPU? A tight repetition of accept4(...) = -1 EMFILE (Too many open files) is the fd-exhaustion spin described above. Count with strace -c -f -p PID -e trace=accept4.
  • Who is connecting? -yy decodes both ends of the returned socket, as in = 4<TCP:[127.0.0.1:8080->127.0.0.1:39820]>.

Architecture mapping

ArchitectureNumberABIEntry point
x64 (x86_64)43commonsys_accept
ARM64 (aarch64)202—sys_accept

Kernel history

Introduced in Linux 1.0.

  1. 1.0

    accept() has been part of Linux since 1.0 with BSD semantics.

  2. 2.6.28

    accept4() was added with explicit flags (SOCK_CLOEXEC, SOCK_NONBLOCK) so callers can set those on the new socket atomically, closing race windows that previously required a separate fcntl().

seccomp & containers

Docker default profile

Allowed

Podman default profile

Allowed

accept() / accept4() are on every default profile. As with other socket-API calls, there's no useful argument-filter — the upstream socket() and bind() filters define the surface. For workloads that should never be a server (one-shot init containers, batch jobs), denying accept() / accept4() at the seccomp layer is a small belt-and-braces over also denying listen().

libseccomp

seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(accept),  0);
seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(accept4), 0);

strace example

$ strace -e accept,accept4 nc -l 127.0.0.1 1234
accept4(3, {sa_family=AF_INET, sin_port=htons(57338), sin_addr=inet_addr("127.0.0.1")}, [16], SOCK_CLOEXEC) = 4

strace shows the peer address decoded (sin_port, sin_addr) and addrlen as [in => out], e.g. [128 => 16]. A server parked in a blocking accept() is simply idle; a tight loop of accept4() = -1 EMFILE means the process ran out of file descriptors while the listener stays readable. -e trace=accept,accept4 catches both variants; -yy decodes both ends of the returned socket.

Security & observability

accept() returning new connected sockets is the canonical entry point for any incoming network traffic. eBPF tracepoint sys_exit_accept fires with the new fd; correlating to the peer sockaddr (from the same call) gives instant attribution of every connection — used by Falco, Tracee, and most container EDRs. fd-exhaustion attacks (the 'slowloris' family) starve the accept loop; monitoring EMFILE / ENFILE return rate is the canary. The double-close-on-accept race that haunted multi-threaded servers in the 2000s is mitigated by always using accept4(SOCK_CLOEXEC).

Errors

EAGAIN
The socket is non-blocking and no connections are queued. Wait via poll/epoll for POLLIN before retrying.
EBADF
—
ECONNABORTED
A queued connection was aborted before accept() picked it up (for example the client reset it). Retry.
EINTR
Interrupted by a signal before a connection arrived.
EINVAL
—
EMFILE
Per-process fd limit reached — common cause of mysterious 'server stops accepting' on busy hosts. Raise RLIMIT_NOFILE.
ENFILE
System-wide fd limit reached.
ENOTSOCK
—
EOPNOTSUPP
—
EPERM
—
EPROTO
Protocol error. On Linux this is one of the pending network errors (with ENETDOWN, EHOSTUNREACH, ENETUNREACH and others) that accept() reports for a single failed connection; the man page says to treat them like EAGAIN and retry.

Related syscalls