Definition
listen(C)
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;
}