C++
TCP server
Learn to write a TCP server.
What is a TCP server?
A TCP server is the side that waits for incoming connections. After creating a socket it binds to a port with bind(), starts waiting with listen(), and accepts incoming connections with accept().
Example: bind(sock, (sockaddr*)&addr, sizeof(addr)); binds the socket to the address. listen(sock, 5); opens the connection queue (5 pending connections). int client = accept(sock, nullptr, nullptr); accepts a client connection and returns a new socket. In the server address, addr.sin_addr.s_addr = INADDR_ANY; makes the server accept connections on all network interfaces.
listen and accept
listen(sock, backlog) puts the socket in a passive state: ready to accept connections. backlog is the queue length. accept(sock, ...) blocks until a client connects and returns a new socket for that connection.
Example: listen(sock, 5); lets up to 5 connections wait in the queue. int client = accept(sock, nullptr, nullptr); returns a new socket when a client connects. This new socket is used for send and recv; the main socket keeps accepting new connections. A server usually loops on accept. This lesson shows the basic flow without a loop.
Exercise Set up a TCP server
Add #include <sys/socket.h> and #include <netinet/in.h>. Create a socket with int sock = socket(AF_INET, SOCK_STREAM, 0);. Define sockaddr_in addr; and set addr.sin_family = AF_INET;, addr.sin_port = htons(8080);, addr.sin_addr.s_addr = INADDR_ANY;. Call bind(sock, (sockaddr*)&addr, sizeof(addr)); and listen(sock, 5);. Print std::cout << "Server ready";.
Show example solution
#include <iostream>
#include <sys/socket.h>
#include <netinet/in.h>
int main() {
int sock = socket(AF_INET, SOCK_STREAM, 0);
sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(8080);
addr.sin_addr.s_addr = INADDR_ANY;
bind(sock, (sockaddr*)&addr, sizeof(addr));
listen(sock, 5);
std::cout << "Server ready";
return 0;
}
Test yourself
-
Complete the bind call
____(sock, (sockaddr*)&addr, sizeof(addr));
Show answer
bind(sock, (sockaddr*)&addr, sizeof(addr));
-
Match each piece to its role
- bind(sock, ...)
- Binds to a port
- listen(sock, 5)
- Waits for connections
- accept(sock, ...)
- Accepts a client
- INADDR_ANY
- All interfaces
-
What does accept return?
- A new client socket
- A connection status code
- A port number
- An IP address
Show answer
A new client socket — accept returns a new socket for the client.
Next lesson: Boost.Asio