Skip to content
Tutorials Center
My learning

Topics

Lesson 131 of 171 ยท Utilities

Network Programming Basics

Learn C++ network programming with POSIX sockets - a RAII socket wrapper, a TCP echo server and client on loopback, reliable send and receive loops, and message framing.

Standard C++ has no networking library. Whenever a C++ program talks over a network, it goes through the operating system's socket API, the same C interface that has existed since the 1980s, or through a library built on top of it such as Boost.Asio or the standalone Asio. Asio is the model behind the networking proposal that C++ has been discussing for years, and it is worth knowing it exists. But under every library there are the same few system calls, and understanding them makes any C++ networking code easier to read and debug.

This lesson uses the POSIX socket API (<sys/socket.h> and friends), which works on Linux and macOS. You will wrap the raw integer file descriptor in a small RAII class so it can never leak, build a TCP echo server and client that talk over the loopback interface inside one program, and learn the two things that trip up almost every beginner: partial reads and writes, and message boundaries. All examples use 127.0.0.1, so nothing leaves your machine. Windows uses Winsock, which looks very similar but has different headers and a startup call.

The shape of a TCP conversation

A socket is an endpoint for communication. With TCP, one side is the server and the other the client:

  1. The server creates a socket, binds it to an address and port, and calls listen.
  2. The client creates a socket and connects to that address.
  3. The server calls accept, which returns a new socket dedicated to that client.
  4. Both sides send and recv bytes, then close.
sequenceDiagram
    participant S as Server
    participant C as Client
    S->>S: socket, bind, listen
    C->>S: connect
    S->>S: accept (new socket per client)
    C->>S: send "hello"
    S->>C: send "hello" (echo)
    C->>S: close
    S->>S: recv returns 0 (peer closed)

The life of one TCP connection. The server's listening socket stays open; each accepted client gets its own socket.

TCP gives you a reliable, ordered stream of bytes. It does not give you messages: if the client sends "ab" and then "cd", the server may receive "abcd" in one call, or "a" then "bcd". Keep that sentence in mind; it drives most of the design later in this lesson.

A RAII wrapper for file descriptors

On POSIX systems a socket is an int returned by socket() or accept(). You must pass it to close() exactly once. That is the classic resource-management problem that RAII solves. The class below owns a descriptor, closes it in the destructor, and is move-only, like std::unique_ptr:

C++ A move-only file descriptor wrapper

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

socketpair is a handy way to practice because it needs no addresses or ports. The wrapper behaves like a smart pointer: copying is deleted, moving transfers ownership, and the destructor closes whatever is still held. Even if an exception is thrown later in a function, the descriptor is closed during stack unwinding.

Checking errors

Every socket call reports failure by returning -1 and setting errno. Forgetting to check is the most common cause of mysterious network bugs, so wrap the check in a helper that turns failure into an exception:

C++
#include <cerrno>
#include <cstring>
#include <system_error>

int check(int result, const char* what) {
    if (result < 0) {
        throw std::system_error(errno, std::generic_category(), what);
    }
    return result;
}

std::system_error carries the errno value and produces a readable message such as bind: Address already in use. The remaining examples use the same idea.

A TCP echo server and client

Now the real thing. The program below starts a server on loopback, asks the operating system for any free port by binding to port 0, and reads the chosen port back with getsockname. A client thread connects, sends a line, and prints the reply. The server runs in the main thread so that the example is one self-contained program (threads are covered in Threads):

C++ Echo server and client on loopback

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Read the main steps once more. The server socket is created with AF_INET (IPv4) and SOCK_STREAM (TCP). htons and ntohs convert 16-bit numbers between your CPU's byte order and network byte order, which is big-endian. shutdown(SHUT_WR) tells the other side that no more data is coming, so its recv eventually returns 0, which means "the peer closed the connection". A negative return means an error, and a positive return is the number of bytes that arrived. Output order of the two println calls is guaranteed here, because the client cannot print before the server has sent its echo.

Partial reads and writes

send is allowed to accept fewer bytes than you asked for, and recv returns whatever is available, which may be less than the sender wrote in one call. The honest way to use them is in loops. This helper pair sends or receives exactly n bytes:

C++
bool send_all(int fd, const char* data, size_t size) {
    while (size > 0) {
        ssize_t n = ::send(fd, data, size, 0);
        if (n < 0) {
            if (errno == EINTR) continue;   // interrupted by a signal: retry
            return false;
        }
        data += n;
        size -= static_cast<size_t>(n);
    }
    return true;
}

bool recv_all(int fd, char* data, size_t size) {
    while (size > 0) {
        ssize_t n = ::recv(fd, data, size, 0);
        if (n == 0) return false;           // peer closed before we got everything
        if (n < 0) {
            if (errno == EINTR) continue;
            return false;
        }
        data += n;
        size -= static_cast<size_t>(n);
    }
    return true;
}

Code that calls send once and assumes everything went through works in tests on a quiet machine and fails under load. Always loop.

Message framing

Because TCP is a stream, you need a rule that says where one message ends and the next begins. Two common rules are a delimiter (HTTP headers end with a blank line, many text protocols end with \n) and a length prefix: send the size first, then the payload. A length prefix is simple and works for binary data. The example sends three messages back to back over a socketpair; the receiver cuts them apart correctly even though the bytes were written without pauses:

C++ Length-prefixed messages

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Three details matter. The length is sent with htonl so both machines agree on its byte order. The receiver rejects absurd lengths before allocating memory, because a hostile or buggy peer could otherwise ask for gigabytes. And an empty message is legal: it is a length of zero followed by nothing, which is not the same as the connection closing.

Beyond one blocking connection

The server above handles one client at a time and blocks inside accept and recv. Real servers choose one of a few strategies:

  • A thread per connection, simple but expensive at thousands of clients.
  • Readiness APIs such as poll, epoll (Linux) or kqueue (BSD and macOS): one thread asks the OS which sockets are ready and handles only those.
  • Asynchronous I/O libraries such as Asio, which wrap the readiness APIs in callbacks or coroutines.

An Asio-style program reads like this. It is shown read-only, because it needs the Asio library, which the runner does not have:

C++
// Needs Asio (standalone or Boost.Asio); not runnable here.
asio::awaitable<void> echo(asio::ip::tcp::socket socket) {
    char data[1024];
    for (;;) {
        std::size_t n = co_await socket.async_read_some(asio::buffer(data), asio::use_awaitable);
        co_await asio::async_write(socket, asio::buffer(data, n), asio::use_awaitable);
    }
}

The names differ, but the ideas are the ones you just used: sockets own a descriptor with RAII, reads may return fewer bytes than you hoped, and you decide how messages are framed. For anything that faces the public internet, also use TLS (for example through OpenSSL) and treat every byte received as untrusted input.

Network code multiplies the risks of undefined behavior: buffer sizes, integer conversions and lengths all come from outside your program. Validate lengths, never assume a recv fills a buffer, and never pass received text to functions that expect a trusted format.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. recv on a TCP socket returns 0. What does that mean?

    A return of 0 means end of stream: the other side closed or shut down its sending direction. Errors are reported with -1, and a positive value is the number of bytes received.
  2. 2. A client calls send twice, writing "ab" and then "cd". What can the server's recv calls return?

    TCP preserves order but not boundaries. Your protocol must define where messages end, for example with a delimiter or a length prefix.
  3. 3. Why is the fd wrapper class made move-only?

    Exactly one owner must close a descriptor. A copy would lead to a double close, which can even close a different, newly opened descriptor with the same number.
  4. 4. What does binding a TCP socket to port 0 do?

    Port 0 asks the OS to assign any available ephemeral port. This is the standard way to avoid port clashes in tests and demos.

Summary

  • Standard C++ has no networking library; programs use the OS socket API directly or a library such as Asio built on it.
  • Wrap a file descriptor in a move-only RAII class so it is always closed exactly once.
  • Check every socket call; failures return -1 with errno, which std::system_error can report clearly.
  • A TCP server uses socket, bind, listen and accept; a client uses socket and connect.
  • TCP is a byte stream: loop on send and recv, and frame messages with delimiters or length prefixes.
  • Convert multi-byte integers with htons, htonl, ntohs and ntohl, and validate every length received.

Next: Threads, where you will run work in parallel, the building block of servers that handle many clients.