TCP server
- C++ course
- Advanced
- Lesson 57/83
- 5 min
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.
Practice 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";.
Starter code
#include <iostream>
// Add socket headers, set up the server
int main() {
// Add socket, bind and listen calls
return 0;
}Sample 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;
}Expected output
Server ready
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the bind call
____(sock, (sockaddr*)&addr, sizeof(addr));
bind(sock, (sockaddr*)&addr, sizeof(addr));
Explanation: bind binds the socket to a port.
2 Match each piece to its role
| Term | Meaning |
|---|---|
bind(sock, ...) |
Binds to a port |
listen(sock, 5) |
Waits for connections |
accept(sock, ...) |
Accepts a client |
INADDR_ANY |
All interfaces |
3 What does accept return?
- A new client socket Correct answer
- A connection status code
- A port number
- An IP address
Explanation: accept returns a new socket for the client.