The Linux Programming Interface

(nextflipdebug5) #1

1156 Chapter 56


In most applications that employ stream sockets, the server performs the passive
open, and the client performs the active open. We presume this scenario in subse-
quent sections, so that instead of saying “the application that performs the active
socket open,” we’ll often just say “the client.” Similarly, we’ll equate “the server”
with “the application that performs the passive socket open.”

Figure 56-1: Overview of system calls used with stream sockets

56.5.1 Listening for Incoming Connections: listen()


The listen() system call marks the stream socket referred to by the file descriptor
sockfd as passive. The socket will subsequently be used to accept connections from
other (active) sockets.

We can’t apply listen() to a connected socket—that is, a socket on which a connect()
has been successfully performed or a socket returned by a call to accept().
To understand the purpose of the backlog argument, we first observe that the
client may call connect() before the server calls accept(). This could happen, for
example, because the server is busy handling some other client(s). This results in a
pending connection, as illustrated in Figure 56-2.

Passive socket
(server)

blocks until
client connects

resumes

(Possibly multiple) data
transfers in either direction

Active socket
(client)

write()

read()

close()

socket()

connect()

socket()

bind()

listen()

accept()

read()

write()

close()

#include <sys/socket.h>

int listen(int sockfd, int backlog);
Returns 0 on success, or –1 on error
Free download pdf