CLOSE
Updated on 17 Jun, 20257 mins read 9 views

What is a Socket?

A socket is a software endpoint that opens a two-way communication link between two programs running on a network. It serves as an abstraction for sending and receiving data across machines.

How Do Sockets Work?

To communicate over a network:

  • The server creates a socket and waits for incoming requests.
  • The client creates a socket and connects to the server’s socket.
  • Once connected, they exchange data over that socket connection.

This applies to both TCP (connection-oriented) and UDP (connectionless) protocols.

Types of Sockets in C/C++

  1. Stream Sockets (SOCK_STREAM)
    1. Used for TCP
    2. Ensures reliable, ordered, and error-checked delivery
    3. Suitable for file transfers, web servers, etc.
  2. Datagram Sockets (SOCK_DGRAM)
    1. Used for UDP
    2. Faster, connectionless, but less reliable
    3. Ideal for real-time apps (games, video calls)
  3. Raw Sockets (SOCK_RAW)
    1. Gives direct access to lower-layer protocols (IP, ICMP)
    2. Used in packet sniffers and custom protocol implementation
    3. Requires root privileges on most OSes

Address Families

When creating a socket, you also define the address family, which tells the OS which protocol family to use:

Address FamilyConstantUse Case
IPv4AF_INETStandard for most TCP/IP programs
IPv6AF_INET6Next-gen networking support
Unix DomainAF_UNIXIPC on the same machine

For internet applications, AF_INET is most common.

Socket Lifecycle: A Simplified View

Here’s a breakdown of how socket communication typically works:

🖥 Server Side:

  1. socket() → Create a socket
  2. bind() → Assign an IP address and port
  3. listen() → Start listening for clients
  4. accept() → Accept a client connection
  5. recv() / send() → Communicate
  6. close() → Close the socket

💻 Client Side:

  1. socket() → Create a socket
  2. connect() → Connect to the server
  3. send() / recv() → Communicate
  4. close() → Close the socket

These APIs are defined in the <sys/socket.h> and <netinet/in.h> headers (on Linux/UNIX systems).

Socket Identifiers

When you create a socket, the OS returns a file descriptor (an integer ≥ 0) that uniquely identifies that socket.

You use this descriptor in all subsequent socket operations.