Setting listen() backlog to 0

Matt Dunn picture Matt Dunn · Feb 28, 2011 · Viewed 8.6k times · Source

When listening on a socket, I would ideally like to limit the backlog to zero, i.e.

listen( socket, 0 );

However, based on the following post, listen() ignores the backlog argument?, this wouldn't work. Is there any way I can reliably achieve a backlog of 0?

Answer

caf picture caf · Mar 1, 2011

The closest you can get is to listen(), accept() and close() in one step. This should provide the same overall effect as a backlog of zero, except that you must re-create and bind the socket each time.

int accept_one(int sockfd, struct sockaddr *addr, socklen_t *addrlen)
{
    int result;

    result = listen(sockfd, 1);

    if (result >= 0)
        result = accept(sockfd, addr, addrlen);

    close(sockfd);

    return result;
}

I am not sure why you would want this, though.