Sockets & Network Programming

a TCP socket

Think of placing a phone call: you dial, the other side picks up, and then you have a private line where everything you say arrives in order and nothing is lost, until one of you hangs up. A TCP socket is that phone line for programs. It is an endpoint of a reliable, connection-oriented conversation built on TCP, the transport protocol that promises your bytes arrive complete, in the right order, with nothing duplicated.

You create one by asking for a stream socket (in code, socket(AF_INET, SOCK_STREAM, 0)). Before any data flows, the two ends must establish a connection with TCP's three-way handshake (SYN, SYN-ACK, ACK), which synchronizes their starting sequence numbers. After that, a TCP socket is identified by a full four-tuple: source IP, source port, destination IP, destination port. That is how one server listening on TCP port 443 keeps thousands of simultaneous clients apart — each client's (IP, port) pair makes a distinct four-tuple. You then send and recv bytes, and the kernel handles acknowledgments, retransmission of lost segments, reordering, and flow control underneath, so your program sees a clean stream.

Why it matters: most familiar protocols — HTTP/1 and HTTP/2, email (SMTP, IMAP), SSH, database connections — run over TCP sockets because they want exactly that reliable, ordered delivery. Two honest cautions. First, the reliability is about delivery, not secrecy: a TCP socket encrypts nothing by itself; TLS does that on top. Second, TCP is a byte stream with no message boundaries, so even though delivery is reliable, your program must still figure out where one message ends and the next begins (message framing) — TCP will happily merge or split your writes.

A chat server on TCP port 5000 has two users connected. Their sockets are (clientA_IP, 51000, server_IP, 5000) and (clientB_IP, 49500, server_IP, 5000). Same server IP and port, but the differing client sides make two distinct, independent streams.

One listening port, many connections — the four-tuple keeps them separate.

Reliable does not mean message-preserving. TCP guarantees the bytes arrive, in order, but not that each recv lines up with a send. Build your own framing or you will eventually read half of one message and the start of the next.

Also called
stream socketSOCK_STREAMTCP 套接字串流通訊端