c

Definition

listen (C)

#include <sys/socket.h>
 
int listen(int sockfd, int backlog);

listen() marks the socket referred to by sockfd as a passive socket, that is, as a socket that will be used to accept incoming connection requests using accept.

Includes: socket.h

Examples

Example: HTTP Server

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <netdb.h>
 
int main() {
    // 1. setup hints for "binding" (AI_PASSIVE)
    struct addrinfo hints = {0};
	hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_PASSIVE; // Wildcard IP (0.0.0.0 or ::)
 
    struct addrinfo *res;
    getaddrinfo(NULL, "8080", &hints, &res);
 
    // 2. create socket, set reuse, bind, and listen
    int s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
    
    // critical: allows restarting server immediately after crash/close
    int opt = 1;
    setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
 
    if (bind(s, res->ai_addr, res->ai_addrlen) < 0) return 1;
    listen(s, 10); // backlog of max 10 queued connections
    freeaddrinfo(res);
 
    printf("Listening on port 8080...\n");
	
	// ...
    
    return 0;
}