Socket Communication
Socket Programming: Connecting Processes Over a Network
When two programs exchange data across a network, or between processes on one machine through the network stack, they do it through sockets. You meet socket programming whenever you write a server, a client that talks to a service at the system-call level, or a chat program in a systems course. This lesson walks through the calls a TCP server and client make, contrasts stream and datagram sockets, and covers the two details that break most first attempts: partial reads and byte order.
The call sequence
A socket is an endpoint for communication that the operating system represents as a file descriptor, so you read and write it with system calls much as you would a file. A TCP server and client make different calls:
- Server: socket() creates the endpoint, bind() attaches a local IP address and port, listen() marks it as passive with a backlog, and accept() waits for a client.
- Client: socket() creates the endpoint, then connect() names the server's address and port, which starts the TCP three-way handshake.
int lfd = socket(AF_INET, SOCK_STREAM, 0);
bind(lfd, (struct sockaddr *)&addr, sizeof addr);
listen(lfd, 16);
int cfd = accept(lfd, NULL, NULL); /* connected socket for this client */Many languages wrap a connected socket in input and output streams, such as Java's getInputStream() or Python's makefile(), so you can use ordinary stream reads and writes. The bytes underneath are the same, and so are the rules below.
Stream and datagram sockets
The second argument to socket() chooses the communication service. For Internet address families (AF_INET or AF_INET6) with the default protocol argument 0, SOCK_STREAM selects TCP and SOCK_DGRAM selects UDP, where each sendto() sends one self-contained datagram. Socket type alone does not select TCP or UDP across all POSIX address families.
Property | SOCK_STREAM (TCP) | SOCK_DGRAM (UDP) |
|---|---|---|
Setup | connect() and accept() required | no connection required; each sendto() names a destination |
Delivery | reliable and in order | may be lost, duplicated or reordered |
Message boundaries | none: one continuous byte stream | kept: one recvfrom() returns one datagram |
Data larger than the buffer | the rest waits for the next recv() | the excess is discarded |
Typical use | file transfer, HTTP | DNS queries, live media |
Partial transfers and byte order
Because TCP keeps no message boundaries, recv may return fewer bytes than you asked for, and data from two sends may arrive merged in one receive. Applications therefore frame their messages, commonly with a fixed-size length header, and loop until the full count has arrived. After k calls returning r1,…,rk bytes of an N-byte message, the bytes still to read are
size_t got = 0;
while (got < len) {
ssize_t r = recv(cfd, buf + got, len - got, 0);
if (r <= 0) break; /* 0: peer closed, -1: error */
got += r;
}For a positive requested length, a return of 0 means the peer closed its sending side, and -1 signals an error. send() on a stream socket can also accept fewer bytes than requested, so robust code loops on writes too.
The IPv4 port field sin_port and address field sin_addr.s_addr use network byte order, which is big-endian. Convert host-order integers with htons() for a 16-bit port or htonl() for a 32-bit IPv4 address; use ntohs() and ntohl() for the reverse conversions. An address produced by inet_pton() is already in network order. Set sin_family directly to AF_INET, without byte-order conversion. Application-protocol fields use the encoding their protocol specifies; apply these conversions only to fields explicitly defined as big-endian integers.
For a 16-bit big-endian field whose bytes arrive as b0 then b1,
Example: Port 443 is 0x01BB. In network order the bytes are 0x01 then 0xBB, so v=256(1)+187=443. A little-endian host that skips ntohs() treats the first byte as least significant and reads 256(187)+1=47873.
What to remember
- Servers call socket, bind, listen and accept; clients call socket and connect.
- Each accepted client gets its own connected descriptor; the listener only queues new clients.
- TCP is a byte stream: frame messages yourself and loop until nleft=0.
- UDP preserves datagram boundaries but not delivery or order.
- IPv4 port and address fields use network byte order; sin_family does not. Follow each application protocol's specified field encodings.
Example: Reading a length-prefixed message over TCP
A chat server and its clients exchange messages over TCP. Each message is a length-prefixed frame: a 4-byte unsigned length header in network byte order, followed by exactly that many payload bytes. The server runs on a little-endian x86 host and reads one header whose bytes arrive in the order 0x00, 0x00, 0x05, 0xDC.
a) How many payload bytes does this message contain?
The header is big-endian, so the first byte is the most significant and each position is worth a power of 256:
The third byte contributes 5 × 256 = ________, and the last byte 0xDC equals ________ in decimal, since 13 × 16 + 12 = 220.
This is the value ntohl() returns for the header, so the payload is 1500 bytes long.
b) The server's payload loop requests the smaller of the remaining count and its 512-byte buffer on each call. The first three recv() calls return 512, 300 and 512 bytes. How many payload bytes remain, and how many should the fourth call request?
The three calls together delivered 512 + 300 + 512 = ________. Using the remaining-bytes relation:
Requesting a full 512 bytes could also read bytes from the next frame if the client has already sent it. A loop that treats all those bytes as the current payload would lose the frame boundary.
The 300-byte return on the second call is not an error. The call delivered 300 bytes; a short read does not establish exactly how many bytes had arrived. Short reads are normal on a byte stream, so the loop updates the remaining count using the number actually returned.
There are 176 payload bytes remaining, so the fourth call should request min(176,512)=176 bytes.
c) A teammate's version copies the four header bytes straight into a uint32_t without calling ntohl(). What length does that version see, and what goes wrong?
A little-endian host treats the byte at the lowest address as least significant, so the four bytes 00 00 05 DC are read as the value 0xDC050000:
The first term is 220 × 16777216 = ________, and the second is 5 × 65536 = ________. Adding them:
The teammate's server interprets the payload length as about 3.7 GB. Depending on its implementation, trusting that incorrect length could cause excessive memory allocation, consume subsequent frames as part of this one, or leave the receiver waiting for more bytes until EOF, an error or a timeout.
Convert the header with ntohl(), then validate the decoded length against the protocol's allowed maximum before allocating memory or reading the payload. The unconverted length is 3691315200 bytes; the correctly decoded payload length is 1500 bytes.
A telemetry client uses a connected TCP socket in nonblocking mode. Every call to recv requests 256 bytes with flags set to zero. Complete the statements with signed integer return values.
After the peer has orderly shut down its sending direction and the client has consumed all queued bytes, recv returns .
If the peer's sending direction remains open but no bytes are available, recv returns and sets errno to EAGAIN or EWOULDBLOCK.
A TCP echo server on port 9000 handles a single client using the standard three-way handshake. Assume all listed socket calls succeed and the server makes its calls sequentially. Put these events in the order they must happen, from the server creating its endpoint to the server releasing the client's descriptor.
Loading ordering steps…