Comprehensive Guide to C++ Network Programming Interview Questions
This article provides an extensive overview of C++ network programming concepts frequently asked in interviews, covering sockets, TCP/UDP differences, I/O multiplexing models, handshake mechanisms, packet framing issues, concurrency strategies, code examples for servers and clients, and performance optimization techniques.
Socket Basics
A socket is an abstract endpoint for network communication, represented in C++ as a file descriptor that can be created, bound, listened to, connected, and used for sending and receiving data over TCP or UDP.
Level‑Triggered vs Edge‑Triggered
Level‑triggered (LT) repeatedly notifies when a descriptor is ready, while edge‑triggered (ET) notifies only on state changes, requiring the application to read/write until EAGAIN.
TCP and UDP Differences
TCP provides reliable, ordered, connection‑oriented communication with flow and congestion control, whereas UDP is connectionless, unordered, and faster, suitable for real‑time applications.
Three‑Way Handshake and Four‑Way Teardown TCP connection establishment uses SYN, SYN‑ACK, and ACK packets; termination uses FIN, ACK, FIN, ACK sequence, with the final side entering TIME_WAIT for 2 MSL to avoid stray packets. Sticky Packet and Packet Splitting Common in stream protocols, solved by fixed‑length messages, delimiters, length headers, or application‑level protocols. TCP Server Example (C++) #include <iostream> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> int serverSocket = socket(AF_INET, SOCK_STREAM, 0); if (serverSocket == -1) { std::cerr << "Failed to create socket." << std::endl; } struct sockaddr_in serverAddress{}; serverAddress.sin_family = AF_INET; serverAddress.sin_port = htons(port); serverAddress.sin_addr.s_addr = INADDR_ANY; int bindResult = bind(serverSocket, (struct sockaddr*)&serverAddress, sizeof(serverAddress)); int listenResult = listen(serverSocket, backlog); int clientSocket = accept(serverSocket, (struct sockaddr*)&clientAddress, &clientAddrLen); close(clientSocket); close(serverSocket); TCP Client Example (C++) #include <iostream> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> int clientSocket = socket(AF_INET, SOCK_STREAM, 0); struct sockaddr_in serverAddress{}; serverAddress.sin_family = AF_INET; serverAddress.sin_port = htons(port); inet_pton(AF_INET, serverIP, &(serverAddress.sin_addr)); int connectResult = connect(clientSocket, (struct sockaddr*)&serverAddress, sizeof(serverAddress)); std::string msg = "Hello Server!"; send(clientSocket, msg.c_str(), msg.length(), 0); char buffer[1024]; int bytesRead = recv(clientSocket, buffer, sizeof(buffer), 0); close(clientSocket); Non‑Blocking I/O Set O_NONBLOCK via fcntl(fd, F_SETFL, flags|O_NONBLOCK) or use ioctl(fd, FIONBIO, &value) . Combine with epoll, select, or poll for event‑driven processing. Asynchronous I/O Use OS‑specific APIs (epoll on Linux, kqueue on macOS, IOCP on Windows) or libraries such as Boost.Asio to perform operations without blocking the thread. IPv4 vs IPv6 IPv4 uses 32‑bit addresses; IPv6 uses 128‑bit addresses. In C++, handle IPv6 with sockaddr_in6 and conversion functions inet_pton / inet_ntop . Serialization Convert objects to byte streams (e.g., JSON, Protocol Buffers) before sending over the network and deserialize on receipt. Multithreaded Server Spawn a thread per connection or use a thread pool; protect shared resources with std::mutex or other synchronization primitives. Synchronization Mechanisms Mutexes, semaphores, condition variables, and atomic operations ensure safe concurrent access. SSL/TLS with OpenSSL #include <openssl/ssl.h> SSL_library_init(); SSL_CTX *ctx = SSL_CTX_new(SSLv23_method()); SSL *ssl = SSL_new(ctx); SSL_set_fd(ssl, sockfd); SSL_accept(ssl); SSL_write(ssl, "data", len); SSL_read(ssl, buf, sizeof(buf)); SSL_shutdown(ssl); SSL_free(ssl); SSL_CTX_free(ctx); HTTP vs HTTPS HTTPS adds SSL/TLS encryption, uses port 443, and requires certificate verification, providing confidentiality and integrity. RESTful API in C++ Define resources, map HTTP methods (GET, POST, PUT, DELETE) to handlers, and use frameworks like CppRESTSDK or Pistache. Load Balancing Distribute requests across multiple servers using hardware load balancers, Nginx/HAProxy, or DNS round‑robin. Performance Tuning Adjust socket buffers, enable TCP fast open, use zero‑copy (sendfile), tune kernel parameters (e.g., tcp_max_syn_backlog), and profile application code. Reverse Proxy Acts as an intermediary, forwarding client requests to backend servers, providing load balancing, caching, and security. Consistency and Availability in Distributed Systems Choose strong consistency (e.g., Paxos, Raft) or eventual consistency based on CAP trade‑offs; use replication and partition tolerance strategies. RPC in C++ Define interfaces with Protocol Buffers or Thrift, generate stubs, serialize arguments, transmit over TCP/HTTP, and deserialize on the server side. Packet Capture Tools like Wireshark, tcpdump, or tshark capture and analyze network traffic. Security and DDoS Mitigation Deploy firewalls, IDS/IPS, rate limiting, SYN cookies, and use DDoS protection services. WebSocket Provides full‑duplex communication over a single TCP connection, useful for real‑time chat, gaming, and live updates. UDP Broadcast and Multicast #include <arpa/inet.h> int sock = socket(AF_INET, SOCK_DGRAM, 0); int broadcast = 1; setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &broadcast, sizeof(broadcast)); struct sockaddr_in addr{}; addr.sin_family = AF_INET; addr.sin_port = htons(12345); addr.sin_addr.s_addr = inet_addr("255.255.255.255"); sendto(sock, "msg", 3, 0, (struct sockaddr*)&addr, sizeof(addr)); close(sock); High‑Concurrency Handling Use epoll with non‑blocking sockets, thread pools, or async frameworks to manage thousands of simultaneous connections. Reactor vs Proactor Reactor notifies when a descriptor is ready and the application performs I/O; Proactor notifies when an asynchronous I/O operation completes, offloading the I/O work to the OS. TCP State Management Understand CLOSE_WAIT, TIME_WAIT, half‑open connections, and use SO_REUSEADDR or tune tcp_tw_reuse to mitigate resource exhaustion.
Deepin Linux
Research areas: Windows & Linux platforms, C/C++ backend development, embedded systems and Linux kernel, etc.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.