Mastering TCP Socket APIs: Server & Client Functions Explained
This article explains the TCP socket programming interface, detailing server and client API functions, their purposes, the three‑way handshake, state transitions, data transmission, segmentation, sticky‑packet issues, and the four‑way termination process, providing code examples and diagrams for clear understanding.
TCP Network Development API
TCP (Transmission Control Protocol) is a connection‑oriented, reliable, byte‑stream transport‑layer protocol.
1.1 TCP Server API
#include <sys/types.h>
#include <sys/socket.h>
// 1
int socket(int domain, int type, int protocol);
// 2
int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen);
// 3
int listen(int sockfd, int backlog);
// 4
ssize_t recv(int sockfd, void *buf, size_t len, int flags);
// 5
int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);
// 6
ssize_t send(int sockfd, const void *buf, size_t len, int flags);
// 7
int close(int fd);
// 8
int shutdown(int sockfd, int how);1.2 TCP Client API
#include <sys/types.h>
#include <sys/socket.h>
// 1
int socket(int domain, int type, int protocol);
// 2
int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen);
// 3
int connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen);
// 4
ssize_t send(int sockfd, const void *buf, size_t len, int flags);
// 5
ssize_t recv(int sockfd, void *buf, size_t len, int flags);
// 6
int close(int fd);
// 7
int shutdown(int sockfd, int how);1.3 Purpose of API Functions
(1) int socket(int domain, int type, int protocol) allocates a file descriptor and creates a TCB.
(2)
int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen)binds a local IP address and port to the socket.
(3) int listen(int sockfd, int backlog) puts the socket into LISTEN state.
(4)
int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen)removes a node from the full‑connection queue and returns a new fd.
(5) ssize_t recv(int sockfd, void *buf, size_t len, int flags) copies data from the receive buffer to user space.
(6)
ssize_t send(int sockfd, const void *buf, size_t len, int flags)copies data from user space to the send buffer.
(7) int close(int fd) prepares a FIN packet and places it in the send buffer.
(8)
int connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen)sends a SYN packet and waits for the three‑way handshake to complete.
TCP Three‑Way Handshake
2.1.1 TCP Three‑Way Handshake
Diagram:
The first handshake is triggered by connect() sending a SYN to the server. The second handshake occurs after the server receives the SYN and sends SYN‑ACK before accept(). The third handshake is the client’s ACK, completing the connection.
TCP Header Overview
0 |1 |2 |3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-------------------------------+-------------------------------+
| Source Port | Destination Port |
+---------------------------------------------------------------+
| Sequence Number |
+---------------------------------------------------------------+
| Acknowledgment Number |
+-------+-----------+-+-+-+-+-+-+-------------------------------+
| Header| Reserve |U|A|P|R|S|F| Window |
| Length| |R|C|S|Y|I| |
+-------------------------------+-------------------------------+
| Checksum | Urgent Pointer |
+---------------------------------------------------------------+
| Option |
+---------------------------------------------------------------+
| Data |
+---------------------------------------------------------------+SYN: synchronize
ACK: acknowledgement
PSH: push
FIN: finish
RST: reset
URG: urgent
Sequence Number: first byte’s sequence number.
Acknowledgment Number: next expected sequence number (usually received Sequence Number + 1).
During the handshake, Linux maintains a half‑connection (SYN) queue and a full‑connection (ACCEPT) queue. The backlog parameter primarily defines the size of the full‑connection queue in modern kernels.
Excessive SYN packets can cause a SYN‑flood DDoS attack, filling the half‑connection queue and preventing legitimate connections.
2.1.2 TCP State Transition Diagram
Key observations: LISTEN can transition to SYN_SEND by sending SYN; SYN_SEND can receive SYN and send SYN‑ACK to become SYN_RECV, allowing both sides to exchange SYN packets.
2.2 TCP Data Transfer
Data is sent and received via send() and recv(). A positive return from send() only indicates data was copied to the kernel buffer, not that it reached the destination; acknowledgments are needed for reliability.
2.2.1 Transmission Control Block (TCB)
The TCB stores socket information and buffers for both ends of a connection, persisting throughout the TCP session.
2.2.2 TCP Segmentation
When data exceeds the send buffer or maximum segment size, TCP splits it into multiple packets; the application typically loops over send() and recv().
2.2.3 TCP Sticky Packets and Solutions
Sticky packets occur when multiple messages are concatenated in the receive buffer. Common solutions include prefixing each packet with its length or adding a delimiter.
// Example length‑prefixed read
ssize_t count = 0;
ssize_t size = 0;
while (count < tcpHdr->length) {
size = recv(fd, buffer, buffersize, 0);
count += size;
}2.3 TCP Four‑Way Handshake
Connection termination involves active and passive close, requiring four packets. The close() call initiates the FIN handshake; the TCB is released only after the four‑way handshake completes.
Typical questions address detection of cable disconnection, client crashes, distinguishing network congestion from host failure, handling many CLOSING states, and the purpose of the TIME_WAIT state to avoid lost LAST_ACK retransmissions.
Summary
Master the three‑way handshake, four‑way termination, state diagram, SYN/ACK packets, API internals, half‑ and full‑connection queues, segmentation, and sticky‑packet handling to build robust TCP applications.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
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.
