Lesson 7 of 18 The System Calls

connect(), listen() and accept()

How a TCP connection is made: connect() on the client, listen() and the backlog on the server, and accept() returning a new socket per client.

35-45 min beginner 0/18 lessons done
Course contents Lesson 7 of 18 · 0 done
On this page (9 sections)
  1. What you will learn
  2. The handshake in one picture
  3. connect(): the client side
  4. listen(): start accepting connections
  5. accept(): one new socket per client
  6. connect() on a UDP socket
  7. Key takeaways
  8. Exercises
  9. Quiz

What you will learn

  • What connect() does and how to try every address a name resolves to.
  • What listen() and its backlog really control.
  • Why accept() returns a new socket and what happens to the listening one.
  • Using connect() on a UDP socket.

The handshake in one picture

 client                                   server
 socket()                                 socket(), bind(), listen()
 connect() ---- SYN ------------------->  (kernel queues the connection)
           <--- SYN-ACK ----------------
           ---- ACK ------------------->  connection complete, waits in the queue
 connect() returns 0                      accept() returns a new fd for it

The three-way handshake is done entirely by the kernels. Your code only sees connect() return on one side and accept() return on the other.

connect(): the client side

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

Returns 0 when the connection is established, or -1 with errno. Common errors:

errnoMeaning
ECONNREFUSEDThe host answered, but nothing listens on that port
ETIMEDOUTNo answer at all (host down, or a firewall silently drops packets)
ENETUNREACH / EHOSTUNREACHNo route to that network or host

Because a name can resolve to several addresses, loop over the results and stop at the first success:

int connect_to(const char *host, const char *port)
{
    struct addrinfo hints, *res, *ai;
    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    if (getaddrinfo(host, port, &hints, &res) != 0)
        return -1;

    int fd = -1;
    for (ai = res; ai != NULL; ai = ai->ai_next) {
        fd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
        if (fd == -1)
            continue;
        if (connect(fd, ai->ai_addr, ai->ai_addrlen) == 0)
            break;
        close(fd);              /* a failed socket can't be reused; make a new one */
        fd = -1;
    }
    freeaddrinfo(res);
    return fd;
}

A blocking connect() to an unreachable host can hang for over a minute. Lesson 12 shows how to put a deadline on it.

listen(): start accepting connections

int listen(int sockfd, int backlog);

listen() turns a bound stream socket into a listening socket. It no longer sends or receives data; its only job is to produce new connections.

The backlog caps how many fully established connections may wait for your program to call accept(). If the queue is full, new clients are delayed or refused. Values like 16–128 are fine for learning; busy servers use larger values (Linux silently caps it at net.core.somaxconn, which defaults to 4096 on current kernels). Passing SOMAXCONN means “the system maximum”.

Server order is always: socket() → setsockopt(SO_REUSEADDR) → bind() → listen() → loop on accept().

accept(): one new socket per client

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

accept() takes the next connection from the queue (blocking if it’s empty) and returns a brand-new descriptor connected to that client. The listening socket stays open and keeps accepting more.

for (;;) {
    struct sockaddr_storage peer;
    socklen_t peer_len = sizeof peer;          /* reset every iteration */
    int client = accept(listener, (struct sockaddr *)&peer, &peer_len);
    if (client == -1) {
        perror("accept");
        continue;
    }
    /* talk to the client on `client`, then close(client) */
}

Pass NULL, NULL for the address arguments if you don’t care who connected.

Think of a restaurant host: the listening socket is the host at the door, and each accept() seats a guest at a new table (descriptor). The host goes straight back to the door.

connect() on a UDP socket

You can call connect() on a datagram socket too. No packets are exchanged; the kernel just remembers a default destination. Afterwards you can use send() / recv() instead of sendto() / recvfrom(), and the socket only receives datagrams from that peer. It also lets the kernel report errors like “port unreachable” back to you as ECONNREFUSED.

Key takeaways

  • connect() performs the TCP handshake; try each getaddrinfo() result and create a new socket per attempt.
  • listen() makes a socket a connection factory; the backlog bounds the queue of finished handshakes.
  • accept() returns a new connected socket per client; the listener keeps listening.
  • connect() on UDP sets a default peer and enables error reporting.

Exercises

  1. Use connect_to() against a port with nothing listening and print strerror(errno). Then try an address that doesn’t respond (for example 10.255.255.1) and time how long it takes to fail.
  2. Write a server that never calls accept(), set backlog to 1, and connect several nc localhost PORT clients. Observe what happens with ss -tn.
  3. Make a UDP client that calls connect() and then send()s to a port with no listener twice. What does the second send() or a recv() report?

Quiz

  1. After accept() returns, which socket do you use to talk to the client?
  2. What happens if you close() a socket after a failed connect() and want to try the next address?
  3. What does the backlog in listen() limit?
Show answers
  1. The new descriptor returned by accept(). The listening socket is only for accepting.
  2. That’s correct practice: after a failed connect() the socket’s state is unspecified, so close it and create a new socket for the next address.
  3. The number of connections that have completed the handshake and are waiting for your program to accept() them.

Finished this lesson?

Mark it complete to track your progress (saved in this browser).