Networking & Sockets

socket, bind, listen, and accept

Setting up a shop to receive customers takes four steps: rent the space, put your number on the door so people can find you, open up and let a queue form, and then serve customers one at a time as they walk in. The server side of a TCP program follows exactly this shape with four calls: socket() rents the space, bind() puts an address on the door, listen() opens for queuing, and accept() serves the next caller.

Walking through it: socket() creates the endpoint and gives you a file descriptor. bind() attaches a specific IP address and port to it, so the OS knows which incoming packets belong to you - this is where you claim, say, port 8080. listen() flips the socket into passive mode and tells the kernel to start accepting connection requests into a waiting queue (you give a backlog size, the queue's depth). Then accept() blocks until a client connects, and returns a brand new socket - a separate file descriptor for that one client. The original socket keeps listening; the new one is used to talk to this particular client. A loop that calls accept() over and over handles client after client.

Why it matters: this four-call dance is the skeleton of essentially every TCP server ever written, from a toy echo server to a production web server. The single most common confusion is forgetting that accept() returns a different socket from the one you listen on - the listening socket is the front door, each accepted socket is a private conversation with one visitor. Get that distinction and the rest of server programming falls into place.

int s = socket(AF_INET, SOCK_STREAM, 0); bind(s, &addr, sizeof addr); listen(s, 128); for (;;) { int c = accept(s, NULL, NULL); /* talk to client over c, then */ close(c); } The listening socket s lives for the whole server; each c is one client.

Four calls set up a server; the loop turns each accept() into one client conversation.

Each accepted socket from accept() must be closed when its client is done, or you leak file descriptors and eventually run out. Closing the listening socket, by contrast, shuts the server down for new connections.

Also called
server-side socket callspassive open伺服器端通訊端呼叫