Knowledge / Computer Science and Engineering / Socket programming

Socket programming

Computer Science and Engineering (B.E./B.Tech) · Computer networks · free study notes for exams, placements and interviews

In short

A socket is the programming interface (API) through which an application hands data to the transport layer and receives it back — the end point identified by the pair (IP address, port number), while a connection is identified by the five-tuple (protocol, local IP, local port, remote IP, remote port). The Berkeley/POSIX socket API (socket, bind, listen, accept, connect, send, recv, close) is the de-facto standard, wrapped by Python's socket, Java's Socket/ServerSocket and Windows Winsock. It matters because every network application a student will ever write or debug — web server, chat app, microservice, game server, IoT device — sits on it. Examined in computer-networks labs (every AICTE/CBCS CSE curriculum has a socket-programming lab), in GATE CS as concept questions on the call sequence, concurrency and the five-tuple, and asked constantly in placement interviews at TCS, Infosys, Wipro, Cognizant and in systems rounds at Amazon, Flipkart, Zoho, Juspay, PhonePe and Zscaler.

Explained

What a socket is, and the types

Addresses, ports and byte order

The TCP call sequence, step by step

Server:

  1. socket() → descriptor in CLOSED state.
  2. setsockopt(SO_REUSEADDR) → lets you rebind a port still in TIME_WAIT (otherwise restart fails with "Address already in use").
  3. bind(fd, addr, len) → attaches a local IP+port. Without it the kernel picks an ephemeral port, which clients cannot guess.
  4. listen(fd, backlog) → marks it passive, creates the queue of completed/pending connections; socket goes to LISTEN. backlog bounds the accept queue (Linux also caps it by somaxconn).
  5. accept(fd, &peeraddr, &len) → blocks until a connection is complete, then returns a new connected descriptor; the listening descriptor stays open for more clients.
  6. recv/send (or read/write) on the *new* descriptor, in a loop.
  7. close() the connected descriptor per client; close the listener on shutdown.

Client:

  1. socket().
  2. (optional bind) — normally skipped; the kernel assigns source IP and an ephemeral port.
  3. connect(fd, servaddr, len) → triggers the TCP three-way handshake; returns when it completes (or fails with ECONNREFUSED if nothing listens, ETIMEDOUT/EHOSTUNREACH if unreachable).
  4. send/recv loop, then close().

The UDP sequence, and connected UDP

Concurrency models for servers

Socket options, buffers and framing

Key points

Formulas and examples

Connection identity: five-tuple = (protocol, local IP, local port, remote IP, remote port). Two connections may share four fields but not all five.
Maximum distinct connections from one client IP to one server IP:port = number of usable ephemeral ports ≈ 65,535 − (reserved/low ports). Units: dimensionless count.
Maximum UDP payload (IPv4) = 65,535 − 8 (UDP header) − 20 (IP header, no options) = 65,507 bytes. Over Ethernet without fragmentation: 1,500 − 20 − 8 = 1,472 bytes.
Maximum TCP payload per segment (MSS) = MTU − IP header − TCP header = 1,500 − 20 − 20 = 1,460 bytes (no options). Units: bytes.
Socket buffer for full-rate transfer (bandwidth-delay product): BDP = bandwidth (bits/s) × RTT (s) / 8 bytes. Set SO_RCVBUF ≥ BDP.
Throughput of a stop-and-wait request/response application = message size / RTT; number of RTTs for an HTTP/1.0 fetch over a new TCP connection = 1 (handshake) + 1 (request/response) = 2 RTTs minimum.

Example 1 — Ports used by three clients on one web server. A server listens on 203.0.113.10:443. Clients A (198.51.100.5) and B (198.51.100.6) connect once each; A opens a second connection.

Example 2 — BDP and buffer sizing. A link from Bengaluru to Mumbai has 200 Mbps capacity and RTT 30 ms.

Example 3 — Framing bug made concrete. A client sends "HELLO" (5 B) then "WORLD" (5 B) with two send calls over TCP; the server calls recv(1024) once.

**Example 4 — File transfer time and number of send calls.** Transfer a 10 MB file (10 × 1,048,576 = 10,485,760 B) over a 100 Mbps path, application buffer 4,096 B.

**Example 5 — select versus thread-per-client at 5,000 connections.** Each thread has a 1 MB stack (Linux default 8 MB virtual, 1 MB commonly configured).

# TCP echo server (iterative) and client - Python 3
import socket, struct

def server(host="", port=9000):              # "" = INADDR_ANY
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind((host, port)); s.listen(5)
    while True:
        conn, addr = s.accept()              # new descriptor per client
        with conn:
            while True:
                data = conn.recv(1024)
                if not data:                 # 0 bytes = peer closed (EOF)
                    break
                conn.sendall(data)           # sendall loops over partial writes

def client(host="127.0.0.1", port=9000, msg=b"HELLO"):
    with socket.create_connection((host, port), timeout=5) as c:
        c.sendall(struct.pack("!I", len(msg)) + msg)   # 4-byte length prefix
        n = struct.unpack("!I", recv_exact(c, 4))[0]
        return recv_exact(c, n)

def recv_exact(sock, n):                     # the correct way to read n bytes
    buf = b""
    while len(buf) < n:
        chunk = sock.recv(n - len(buf))
        if not chunk:
            raise ConnectionError("peer closed early")
        buf += chunk
    return buf
# UDP server and client - no listen(), no accept()
srv = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
srv.bind(("", 9001))
data, peer = srv.recvfrom(65535)             # one datagram, with sender address
srv.sendto(data.upper(), peer)
AspectTCP socket (SOCK_STREAM)UDP socket (SOCK_DGRAM)
Calls usedsocket, bind, listen, accept, connect, send, recvsocket, bind, sendto, recvfrom
ConnectionThree-way handshake via connect/acceptNone
BoundariesByte stream - app must frameOne send = one datagram
ReliabilityRetransmission, ordering, flow and congestion controlNone (app must handle loss)
Descriptor per clientYes (from accept)No - one socket serves all peers
Typical server modelConcurrent (fork/thread/epoll)Iterative
Used byHTTP, SSH, SMTP, FTP, database driversDNS, DHCP, SNMP, VoIP, games, QUIC base
CallSideBlocks?Returns
socketbothnodescriptor
bindmainly serverno0 or error
listenserverno0; socket becomes passive
acceptserveryes (unless non-blocking)new connected descriptor + peer address
connectclientyes for TCP (handshake); instant for UDP0 or error
recvbothyes until data/EOFbyte count; 0 = peer closed
sendbothyes if send buffer fullbytes actually queued
close / shutdownbothno0 or error

Where it is used

Interview questions

Common mistakes

Related topics

TCP, UDP, HTTP and DNS · OSI and TCP/IP models · IP addressing and subnetting · Operating systems: processes, threads and I/O multiplexing · Network security: firewalls, VPN and IDS · Distributed systems and RPC/REST APIs

Open in the Knowledge reader →Find jobs →