Course contentsShow
← C
Lesson 1112 of 1,21915. Systems ProgrammingFree lesson

Listening for connections

Listening for connections

What you'll learn: How to tell the operating system that your application is ready to accept incoming network requests.

The Waiting Room

In previous lessons, you created a socket and bound it to an address. However, your program isn't "open for business" just yet. By default, a socket is an active endpoint—something that reaches out to others. To turn it into a server, you must flip a switch that tells the OS to wait for others to reach out to you.

Think of it like a doctor’s office. You have a building (the socket) and an address (the bind). But unless you hire a receptionist to sit at the front desk and manage the queue, patients will just walk into a locked door. The listen() function is how you hire that receptionist.

The Backlog

When you call listen(), you provide two arguments: the socket file descriptor and a backlog.

The backlog is the size of the "waiting room." If five people try to connect at the exact same moment, but your program is busy processing the first one, the other four need a place to wait. If the waiting room is full, the OS will reject any additional incoming connections with an error.

Implementation

Here is how you transition a socket into a listening state:

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

int main() {
    int server_fd;
    // ... [socket() and bind() would happen here] ...

    // We set the backlog to 10.
    // This means 10 pending connections can wait in the queue.
    int backlog = 10;

    if (listen(server_fd, backlog) < 0) {
        perror("Listen failed");
        return 1;
    }

    printf("Server is now listening for incoming connections...\n");
    
    return 0;
}

How many should wait?

Choosing a backlog size is a balancing act. In the old days of C programming, this number was typically very small (like 5). In modern high-traffic systems, it might be hundreds or thousands.

If the backlog is too small, you'll drop connections during busy spikes. If it's too large, you might consume too much system memory holding onto people who have been waiting so long they've already given up. For most learning projects, a value between 5 and 10 is perfect.

Key takeaway

The listen() function marks a socket as passive, allowing it to queue incoming connection requests in a backlog until the program is ready to process them.