Networking in C · advanced · ~15 min

TCP server

Accept and serve client connections.

Lesson

Five calls: socket(), optionally setsockopt(SO_REUSEADDR), bind() to your local address, listen() (mark passive, set backlog), accept() to pick up the next client.

For local exercises, bind to INADDR_LOOPBACK so you can never accidentally expose the server outside the machine.

Code examples

int s = socket(AF_INET, SOCK_STREAM, 0);
int yes = 1; setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof yes);
struct sockaddr_in a = {0};
a.sin_family = AF_INET; a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
a.sin_port = htons(8080);
bind(s, (struct sockaddr*)&a, sizeof a);
listen(s, 16);
int c = accept(s, NULL, NULL);

Common mistakes

  • Binding to INADDR_ANY when you meant loopback. INADDR_ANY listens on every interface.