Accepting client connections
What you'll learn: How to pick up the "ringing phone" of a network socket and establish a dedicated communication channel with a client.
The waiting game
In previous lessons, you learned how to bind() a socket to an address and listen() for incoming traffic. At this stage, your server is like a pizza shop that is open for business, but the phone is just ringing on the hook. To actually talk to a customer, you need to pick up the receiver.
In C networking, this is done with the accept() function. This function is "blocking," meaning your program will pause and wait there until a client attempts to connect.
The secret of the "Second Socket"
A common point of confusion is what happens when a connection is made. When you call accept(), it doesn't use your original "listening" socket for the conversation. Instead, it creates a brand new socket specifically for that one client.
Think of your listening socket as the shop's main front door. People walk through it to enter, but you don't want them standing in the doorway blocking others. Once a customer enters, you lead them to a specific table (the new socket) to take their order. This allows the front door to stay clear so other customers can keep walking in.
Implementing accept()
The accept() function requires a structure to store the client's address information, allowing you to see who is connecting (like their IP address).
#include <sys/socket.h>
#include <netinet/in.h>
// Assuming 'server_fd' is already bound and listening
struct sockaddr_in client_addr;
socklen_t addr_size = sizeof(client_addr);
// This line pauses execution until a client connects
int client_fd = accept(server_fd, (struct sockaddr *)&client_addr, &addr_size);
if (client_fd < 0) {
// Handle error: connection failed
}
// You now use 'client_fd' to send() and recv() data!
// 'server_fd' remains open to accept more new people.
Why two sockets?
By returning a new file descriptor (client_fd), the operating system lets you manage multiple clients at once. You can keep the client_fd in a list of active customers while your main loop goes back to accept() on the server_fd to wait for the next person in line.
Key takeaway
The accept() function blocks until a client connects, then returns a new socket descriptor specifically for communicating with that client.