Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How Linux Uses Sockets?
Linux is an open-source operating system that has gained immense popularity for its stability and security. It is widely used in various fields such as web servers, embedded systems, and supercomputers.
One of the key aspects of Linux is its efficient usage of sockets for interprocess communication. Sockets provide a flexible way to establish communication channels between different processes running on the same or different machines connected over a network.
What are Sockets?
Sockets are a fundamental concept in Linux networking, allowing communication between processes on different computers over a network. In simple terms, a socket is an endpoint of a two-way communication link that is established between two processes.
A socket consists of an IP address and port number combination. The IP address identifies the remote computer while the port number specifies which program or service on that computer to connect to.
In technical terms, a socket is defined as "an endpoint for sending or receiving data across a network". It's essentially an abstraction layer that allows programs to interact with the networking protocols at a high level without worrying about low-level details.
Types of Sockets in Linux
| Socket Type | Protocol | Reliability | Use Case |
|---|---|---|---|
| Stream (SOCK_STREAM) | TCP | Reliable, ordered | Web servers, file transfers |
| Datagram (SOCK_DGRAM) | UDP | Unreliable, fast | DNS queries, video streaming |
| Raw (SOCK_RAW) | ICMP, IGMP | Direct access | Network tools (ping, traceroute) |
| Sequenced (SOCK_SEQPACKET) | SCTP | Reliable packets | Telecom applications |
| Unix Domain | Local | High-speed IPC | Local process communication |
How Sockets Work in Linux
Socket Creation Process
Sockets are created through the socket() system call, which takes three arguments: the address family (AF_INET for IPv4, AF_UNIX for local), socket type (SOCK_STREAM, SOCK_DGRAM), and protocol (usually 0 for default).
Socket File Descriptors
In Linux, sockets are treated as file descriptors, allowing them to be used with standard I/O functions. Each socket has a unique file descriptor that acts as a handle for communication operations. The socket API uses system calls like bind(), listen(), accept(), connect(), send(), and recv() to manage communication.
Socket Communication Protocols
TCP/IP Protocol
The Transmission Control Protocol/Internet Protocol (TCP/IP) provides reliable communication over networks. TCP uses a three-way handshake to establish connections and includes error detection, correction, and flow control mechanisms. Data arrives in the correct order without loss.
UDP Protocol
User Datagram Protocol (UDP) offers fast but unreliable communication. Unlike TCP, UDP has no error correction or ordering guarantees, but it provides lower latency and less overhead, making it suitable for real-time applications like video streaming and gaming.
Socket Programming Examples
Here are practical examples demonstrating socket programming in Linux using C language:
Creating a Socket
#include <sys/socket.h>
#include <stdio.h>
#include <unistd.h>
int main() {
int sockfd;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if(sockfd == -1) {
printf("Failed to create TCP Socket<br>");
return -1;
} else {
printf("TCP Socket Created Successfully<br>");
}
close(sockfd);
return 0;
}
Binding a Socket
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
int main() {
int sockfd;
struct sockaddr_in server;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if(sockfd == -1) {
printf("Failed to create TCP Socket<br>");
return -1;
}
memset(&server, 0, sizeof(server));
server.sin_family = AF_INET;
server.sin_port = htons(8000);
server.sin_addr.s_addr = INADDR_ANY;
if(bind(sockfd, (struct sockaddr*)&server, sizeof(server)) == -1) {
perror("Bind Failed");
return -1;
} else {
printf("Bind Successful<br>");
}
close(sockfd);
return 0;
}
Server Socket with Accept
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
int main() {
int sockfd, newsockfd, portno;
socklen_t len;
char buffer[256];
struct sockaddr_in serv_addr, client_addr;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if(sockfd == -1) {
printf("Failed to create TCP Socket<br>");
return -1;
}
memset(&serv_addr, 0, sizeof(serv_addr));
portno = 8000;
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(portno);
serv_addr.sin_addr.s_addr = INADDR_ANY;
if(bind(sockfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) == -1) {
perror("Bind Failed");
return -1;
}
listen(sockfd, 5);
len = sizeof(client_addr);
newsockfd = accept(sockfd, (struct sockaddr*)&client_addr, &len);
if(newsockfd == -1) {
printf("Error in Accepting Client Connection<br>");
return -1;
} else {
printf("Client Connected Successfully<br>");
memset(buffer, 0, 256);
read(newsockfd, buffer, 255);
printf("Message from client: %s", buffer);
write(newsockfd, "Hello from server<br>", 18);
close(newsockfd);
}
close(sockfd);
return 0;
}
Key System Calls
socket()Creates a new socket endpointbind()Assigns a local address to a socketlisten()Puts socket in passive mode to accept connectionsaccept()Accepts incoming connection and creates new socketconnect()Initiates connection to remote socketsend()/recv()Sends and receives data over connected socketsclose()Closes socket and releases resources
Conclusion
Linux uses sockets as a powerful abstraction for network communication, supporting various protocols like TCP, UDP, and local domain sockets. The socket API provides a consistent interface for both local and network communication, making it fundamental to Linux system programming. Understanding socket types, system calls, and programming patterns is essential for developing network applications on Linux systems.
