Enabling local and network communication between unrelated processes—even across machines.
📘 What Are Sockets?
Sockets are an IPC mechanism that allows communication between two endpoints, which can be:
- Processes on the same machine (via Unix domain sockets)
- Processes on different machines (via TCP/IP sockets)
Sockets are foundational for network communication, powering everything from web servers to chat apps. Unlike other IPC methods that focus on local memory or queues, sockets provide a universal interface for bidirectional data exchange, either locally or over the internet.
🔄 Real-Life Analogy
Think of sockets like phone lines. Each phone has an address (phone number), and you can dial to connect and talk. Sockets work similarly — they establish a connection between endpoints, allowing them to send and receive messages.
🧰 How Sockets Work
1. Create a Socket
- A socket is created using
socket()
system call.
2. Bind to an Address
- The server binds the socket to an IP address and port using
bind()
.
3. Listen for Connections (Server)
- The server listens using
listen()
and accepts clients usingaccept()
.
4. Connect to Server (Client)
- Clients connect using
connect()
to the server's IP and port.
5. Exchange Data
- Both sides use
send()
andrecv()
(orread()
/write()
) to communicate.
🛠️ Example: TCP Socket Communication in C
Server (C)
#include <stdio.h>
#include <netinet/in.h>
#include <string.h>
#include <unistd.h>
int main() {
int server_fd, client_fd;
struct sockaddr_in addr;
char buffer[1024] = {0};
const char* response = "Hello from server!";
server_fd = socket(AF_INET, SOCK_STREAM, 0);
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = INADDR_ANY;
addr.sin_port = htons(8080);
bind(server_fd, (struct sockaddr*)&addr, sizeof(addr));
listen(server_fd, 5);
client_fd = accept(server_fd, NULL, NULL);
read(client_fd, buffer, sizeof(buffer));
printf("Received: %s\n", buffer);
send(client_fd, response, strlen(response), 0);
close(client_fd);
close(server_fd);
return 0;
}
Client (C)
#include <stdio.h>
#include <netinet/in.h>
#include <string.h>
#include <unistd.h>
int main() {
int sock_fd;
struct sockaddr_in server_addr;
char buffer[1024] = {0};
sock_fd = socket(AF_INET, SOCK_STREAM, 0);
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(8080);
server_addr.sin_addr.s_addr = INADDR_ANY;
connect(sock_fd, (struct sockaddr*)&server_addr, sizeof(server_addr));
send(sock_fd, "Hello from client!", 18, 0);
read(sock_fd, buffer, sizeof(buffer));
printf("Server replied: %s\n", buffer);
close(sock_fd);
return 0;
}
Types of Sockets
Type | Description |
---|---|
TCP (SOCK_STREAM) | Reliable, connection-oriented (like phone call) |
UDP (SOCK_DGRAM) | Fast, connectionless (like postal mail) |
UNIX Domain | Local socket (no networking; used for IPC on same host) |
🔐 Security Considerations
- Use TLS/SSL for encrypted communication over TCP.
- Validate and sanitize all incoming data to prevent injection attacks.
- Use firewall rules to control port access.
- Apply rate limiting to prevent DoS attacks.
✅ Advantages of Sockets
✅ Feature | 📌 Description |
---|---|
Network Communication | Can work across machines via IP networks |
Bidirectional | Both ends can send and receive messages |
Scalable | Suitable for client-server and peer-to-peer models |
Standardized | Supported across virtually all OSes and languages |
❌ Limitations / Challenges
❌ Limitation | 📌 Description |
---|---|
More Complex Setup | Requires managing ports, IPs, error handling |
Latency | Slower than memory-based IPC due to network stack |
Security Risks | Vulnerable to spoofing, sniffing, if not encrypted |
Resource Intensive | Each socket connection consumes system resources |
🔍 Use Cases for Sockets
Scenario | Why Use Sockets? |
---|---|
🌐 Web Servers / APIs | Accept client connections from browsers |
💬 Chat Applications | Real-time text exchange between users |
🧪 Distributed Systems | Communicate between services across servers |
📊 Telemetry / Monitoring | Send system metrics to remote collectors |
🧠 AI Inference APIs | Serve ML model results over TCP sockets |
🔁 Sockets vs Other IPC Methods
IPC Type | Local or Remote | Bidirectional | Performance | Complexity | Use Case |
---|---|---|---|---|---|
Sockets | ✅ Both | ✅ Yes | ⭐⭐ | 🔧🔧🔧 | Network communication |
Pipes | ❌ Local only | 🚫 Usually | ⭐⭐⭐ | 🔧 | Simple process pipelines |
Shared Memory | ❌ Local only | ✅ Yes | ⭐⭐⭐⭐⭐ | 🔧🔧🔧 | High-speed data sharing |
Message Queues | ❌ Local only | ✅ Yes | ⭐⭐ | 🔧🔧 | Structured data flow |
🧠 Best Practices
- ✅ Always check return values from socket operations.
- 🔐 Use TLS for internet-exposed services.
- 🧹 Close unused socket descriptors to avoid leaks.
- ⚖️ Use non-blocking I/O or event loops for scalable systems.
- 🛡️ Authenticate clients for sensitive services.
🏁 Final Thoughts
Sockets are the backbone of modern network communication — not just between processes on the same machine but also across the internet. Their flexibility, bidirectional support, and cross-platform compatibility make them a go-to IPC mechanism for everything from local daemons to global web applications.
Use sockets when you need:
- Communication between unrelated or remote processes
- Scalability across machines
- Full control over data transmission