0Pricing
C++ Academy · Lesson

BSD Sockets API in C++

Use socket, bind, listen, accept, connect, send, and recv in C++ programs.

BSD Sockets API in C++ is a free C++ Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C++ Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

What is the Sockets API?

The BSD sockets API is the de facto standard for network programming. Available on Linux, macOS, BSDs, and (with minor adjustments) Windows via Winsock.

Required Headers

Include the platform headers and use POSIX types.

#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>

Creating a Socket

The socket call returns a file descriptor. Pass family (IPv4), type (TCP or UDP), and protocol (0 for default).

int sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0) {
    perror("socket");
    return 1;
}

Address Structures

struct sockaddr_in holds an IPv4 address and port. Cast to struct sockaddr* when passing to functions.

struct sockaddr_in addr{};
addr.sin_family = AF_INET;
addr.sin_port = htons(8080);
inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);

Byte Order: Host vs Network

Network byte order is big-endian. Use htons, htonl, ntohs, ntohl to convert.

Connecting a Client

Use connect to initiate a TCP connection.

if (connect(sock, (sockaddr*)&addr, sizeof(addr)) < 0) {
    perror("connect");
    close(sock);
    return 1;
}

Sending and Receiving

send and recv exchange bytes. Both can return less than requested — always loop.

const char* msg = "Hello";
send(sock, msg, strlen(msg), 0);

char buffer[1024];
ssize_t n = recv(sock, buffer, sizeof(buffer)-1, 0);
buffer[n] = '\0';

Binding and Listening (Server)

A server binds to an address, listens, and accepts.

int srv = socket(AF_INET, SOCK_STREAM, 0);
bind(srv, (sockaddr*)&addr, sizeof(addr));
listen(srv, 10);
int client = accept(srv, nullptr, nullptr);

Closing the Socket

Call close on Unix or closesocket on Windows.

close(sock);

Error Handling

Sockets functions return -1 on error and set errno. Check every return value.

Wrapping in RAII

Bare file descriptors are easy to leak. Wrap them in a RAII type with a close in the destructor — or use std::unique_ptr with a custom deleter.

struct SocketCloser {
    void operator()(int* fd) const { if (*fd >= 0) ::close(*fd); }
};
using UniqueSocket = std::unique_ptr<int, SocketCloser>;

Windows Differences

On Windows:

  • Include <winsock2.h> and link ws2_32
  • Call WSAStartup before use
  • Use closesocket instead of close
  • Socket type is SOCKET (unsigned)

Quick Check

Which function call initiates a TCP connection from a client to a server?

Recap

The BSD sockets API offers low-level networking primitives. Create a socket, configure an address, then connect (client) or bind+listen+accept (server). Convert byte order with the htons family. Wrap descriptors in RAII to prevent leaks.

Frequently asked questions

Is the “BSD Sockets API in C++” lesson free?

Yes — the full text of “BSD Sockets API in C++” is free to read here on the web, and the C++ Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C++ Academy course, upgrade to CoddyKit PRO.

What will I learn in “BSD Sockets API in C++”?

Use socket, bind, listen, accept, connect, send, and recv in C++ programs. You practise C++ Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start C++ Academy?

No prior experience is required. C++ Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “BSD Sockets API in C++” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this C++ Academy lesson?

Yes. Every C++ Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. BSD Sockets API in C++
  2. Building a TCP Echo Server
  3. Asynchronous IO with epoll and kqueue
  4. Using Boost Asio for Modern Async IO
← Back to C++ Academy