Skip to main content
Be Bitwise
C++Networking in C++

Socket Abstraction in C++

The socket API in C++ is the C library, byte for byte. What we can do is wrap it in RAII classes so the cleanup story stops being a footgun.

The Raw C API

The underlying calls are identical to C:

cpp
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
// ... use socket ...
close(sockfd);

RAII Socket Wrapper

cpp
#include <stdexcept>
#include <sys/socket.h>
#include <unistd.h>
class Socket {
int fd = -1;
public:
Socket() : fd(socket(AF_INET, SOCK_STREAM, 0)) {
if (fd < 0) throw std::runtime_error("socket() failed");
}
// Wrap an existing file descriptor (e.g., from accept())
explicit Socket(int existing_fd) : fd(existing_fd) {
if (fd < 0) throw std::runtime_error("invalid fd");
}
~Socket() { if (fd >= 0) close(fd); }
// Move-only (sockets should not be copied)
Socket(Socket &&other) noexcept : fd(other.fd) { other.fd = -1; }
Socket &operator=(Socket &&other) noexcept {
if (this != &other) {
if (fd >= 0) close(fd);
fd = other.fd;
other.fd = -1;
}
return *this;
}
Socket(const Socket &) = delete;
Socket &operator=(const Socket &) = delete;
int get() const { return fd; }
};
Key Concept

The Socket is move-only because a file descriptor, like a file handle, has exactly one rightful owner. Same semantics as unique_ptr: if a resource can't be duplicated, the type wrapping it shouldn't be copyable either.

Address Wrapper

cpp
#include <arpa/inet.h>
#include <stdexcept>
#include <string>
class InetAddress {
sockaddr_in addr{};
public:
InetAddress(const std::string &ip, uint16_t port) {
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
// inet_pton returns 1 on success, 0 if the string isn't a valid IPv4 address
if (inet_pton(AF_INET, ip.c_str(), &addr.sin_addr) != 1) {
throw std::invalid_argument("bad IPv4 address: " + ip);
}
}
InetAddress(uint16_t port) {
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = INADDR_ANY;
}
const sockaddr *as_sockaddr() const {
return reinterpret_cast<const sockaddr *>(&addr);
}
socklen_t size() const { return sizeof(addr); }
};

Using the Wrappers

cpp
void connect_example() {
Socket sock;
InetAddress addr("127.0.0.1", 8080);
if (connect(sock.get(), addr.as_sockaddr(), addr.size()) < 0) {
throw std::runtime_error("connect failed");
}
std::string msg = "Hello!";
send(sock.get(), msg.c_str(), msg.size(), 0);
}
// Socket automatically closed by destructor

The RAII wrappers guarantee the socket closes, exception or no exception. In C, you'd be sprinkling close() calls down every error branch and praying you didn't miss one.

You can't reach a server from the runner, but socketpair() hands you two connected sockets without any networking at all. This version wraps both ends, moves one, and throws partway through, the same way a failed connect() would. Before you run it, predict which fds the destructors close and in what order.

Try itMove the throw above the send() call, or delete it: either way both fds end up closed. Then try copying a Socket instead of moving it and read the compiler error.
C++ (GCC 9.2.0)