C++ Academy · Lesson

BSD Sockets API in C++

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

Lesson 1 of 414 steps

BSD Sockets API in C++ is a free C++ Academy lesson on CoddyKit. This is lesson 1 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the C++ Academy learning path, and your progress syncs across the web and the CoddyKit app. The C++ Academy course includes 4 lessons in total.

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.

Free to start

Learn C++ with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
51
Lessons
203

Frequently Asked Questions

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

Yes — any 3 lessons of the C++ Academy learning path, including “BSD Sockets API in C++”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The C++ Academy course includes 4 lessons in total.

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, so you can start here or from the beginning and move at your own pace. This is lesson 1 of 4.

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