Topics / Linux System Programming / Q12
What is the sequence of socket calls for a TCP server and client?
Short answer: Server: socket() → bind() (choose IP and port) → listen() → accept() (blocks until a client connects, returns a new socket for that connection) → read()/write() (or recv/send) → close(). Client: socket() → connect() (TCP three-way handshake) → write()/read() → close().
Server Client
socket() socket()
bind(port 8080)
listen()
accept() ◄──── SYN / SYN-ACK / ACK ──── connect()
recv() ◄──────── request ─────────── send()
send() ───────── response ─────────► recv()
close() ◄──────── FIN/ACK ──────────► close()
Minimal TCP echo server
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
int main(void)
{
int ls = socket(AF_INET, SOCK_STREAM, 0);
int on = 1;
setsockopt(ls, SOL_SOCKET, SO_REUSEADDR, &on, sizeof on);
struct sockaddr_in a = { .sin_family = AF_INET, .sin_port = htons(8080),
.sin_addr.s_addr = htonl(INADDR_ANY) };
if (bind(ls, (struct sockaddr *)&a, sizeof a) < 0) { perror("bind"); return 1; }
listen(ls, 16); /* backlog of pending connections */
for (;;) {
int c = accept(ls, NULL, NULL); /* blocks */
if (c < 0) continue;
char buf[512];
ssize_t n;
while ((n = recv(c, buf, sizeof buf, 0)) > 0)
send(c, buf, (size_t)n, 0);
close(c);
}
}
Details interviewers check
- Byte order: ports and addresses are in network byte order (big-endian):
htons,htonl,ntohs. SO_REUSEADDRlets the server restart immediately instead of failing with "Address already in use" while old connections are inTIME_WAIT.- TCP is a byte stream: one
send()of 1000 bytes may arrive as severalrecv()calls, and several sends may arrive together. Applications need framing (length prefix or delimiter). - Partial writes:
send()may send fewer bytes than requested; loop until all are sent. SIGPIPE: writing to a connection the peer closed kills the process unless you ignoreSIGPIPEor useMSG_NOSIGNAL.- UDP is different:
socket(AF_INET, SOCK_DGRAM, 0), nolisten/accept/connectneeded,sendto/recvfromwith addresses; each datagram is delivered whole or not at all.
Handling many clients: one process per client (fork() after accept), one thread per client, or one thread with select/poll/epoll (see the next question).