C powers the networking stack, web servers, and security tools. Today you write a TCP server, explore socket programming, and examine how real-world C security vulnerabilities arise and how modern tooling prevents them.
socket() creates a network endpoint. bind() assigns an address. listen() marks it passive. accept() waits for connections. connect() initiates a connection. send()/recv() transfer data. Close with close(). The socket API is identical across Linux, macOS, and BSD — it has not changed fundamentally since 4.2 BSD (1983). Every network program in any language ultimately calls these same kernel interfaces.
The most common C vulnerabilities: format string bugs (printf(user_input) instead of printf('%s', user_input) — attacker controls format specifiers), integer overflow (int a = INT_MAX; a++ is undefined behavior), off-by-one errors (<=n should be C11 added: _Atomic types for lock-free programming, _Static_assert for compile-time checks, thread_local storage, anonymous structs/unions, and improved Unicode support. C23 (ratified 2023) adds: typeof(), #embed for binary file inclusion, nullptr literal (replacing NULL for pointers), bool/true/false as keywords, constexpr for constants. Use -std=c23 or -std=c11 with recent gcc/clang. Write a concurrent key-value store server in C: accepts TCP connections, parses 'SET key value' and 'GET key' commands, stores data in a hash table, and handles 10 simultaneous clients using threads with proper mutex locking.Modern C: C11 and C23
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#define PORT 8080
#define BUFSIZE 4096
int main(void) {
int server = socket(AF_INET, SOCK_STREAM, 0);
int opt = 1;
setsockopt(server, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
struct sockaddr_in addr = {
.sin_family = AF_INET,
.sin_port = htons(PORT),
.sin_addr = {INADDR_ANY}
};
bind(server, (struct sockaddr*)&addr, sizeof(addr));
listen(server, 10);
printf("Listening on :%d\n", PORT);
while (1) {
int client = accept(server, NULL, NULL);
char buf[BUFSIZE];
ssize_t n = recv(client, buf, sizeof(buf)-1, 0);
if (n > 0) {
buf[n] = '\0';
char resp[] = "HTTP/1.1 200 OK\r\nContent-Length: 13\r\n\r\nHello, World!";
send(client, resp, sizeof(resp)-1, 0);
}
close(client);
}
}Day 5 Summary