Socket Basics
A Socket is a logical endpoint for communication that enables two programs to exchange data over a network.
Think of it like an electrical socket on a wall. Just as you plug a device in to get electricity, software plugs into a network socket to get network connectivity.
1. The Core Formula of a Socket
A socket is defined by the combination of two key pieces of information:
$$ \text{Socket} = \text{IP Address (Host Location)} + \text{Port Number (Process Location)} $$
- Example:
192.168.1.10(IP) +80(Port) =192.168.1.10:80(Socket Address) - Role: The operating system uses this socket information to determine exactly which connection (session) of which program the incoming data belongs to.
2. Types of Sockets (Based on Transport Layer)
There are two primary types of sockets used depending on the underlying protocol.
| Type | Constant (in C) | Protocol | Characteristics | Analogy |
|---|---|---|---|---|
| Stream Socket | SOCK_STREAM |
TCP | Connection-oriented, Reliable, Ordered | Phone Call (Connect then talk) |
| Datagram Socket | SOCK_DGRAM |
UDP | Connectionless, Fast, Unreliable | Mail/Letter (Send and forget) |
3. Socket Communication Flow (Server vs. Client)
Socket communication follows a specific procedure between the Server (Provider) and the Client (Requester).
-
Server:
socket(): Creates a socket. (Install a phone)bind(): Assigns an IP and Port number to the socket. (Assign a phone number)listen(): Puts the socket in a waiting state for incoming requests. (Wait for the ring)accept(): Accepts the client's request to establish a connection. (Pick up the phone)
-
Client:
socket(): Creates a socket.connect(): Requests a connection to the server's IP and Port. (Dial the number)
-
Data Exchange: Once connected, data is exchanged using
send()/recv()functions.