Unix Domain Socket (UDS) / IPC Socket
Saw this from https://docs.docker.com/engine/install/linux-postinstall/
Unix domain sockets are a specific type of socket that operates only for inter-process communication (IPC) within the same machine.
With this socket type, we bind to a path instead of an IP address and port.
UDS vs. Network Sockets?
Network sockets rely on networking protocols such as TCP or UDP and typically use an IP address and port number for addressing. On the other hand, UDS sockets bind file system paths.
“The Docker daemon binds to a Unix socket, not a TCP port. By default it’s the root
user that owns the Unix socket, and other users can only access it using sudo
. The Docker daemon always runs as the root
user.”
What is the bandwith of IPC sockets? Bandwidth (from ChatGPT):
IPC Socket Bandwidth Can achieve up to several GB/s, depending on system resources.
To list out the local unix sockets:
Linux
netstat -a -p --unix
MacOS
netstat -a -f unix
Example using Unix domain sockets:
#include <iostream>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
int main() {
const char *socket_path = "/tmp/my_socket";
if (fork() == 0) {
// Child process: Connect to the server and send a message
int sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
struct sockaddr_un addr;
addr.sun_family = AF_UNIX;
strcpy(addr.sun_path, socket_path);
connect(sockfd, (struct sockaddr*)&addr, sizeof(addr));
const char *msg = "Hello from client!";
write(sockfd, msg, strlen(msg));
close(sockfd);
} else {
// Parent process: Create a server and accept connections
int sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
struct sockaddr_un addr;
addr.sun_family = AF_UNIX;
strcpy(addr.sun_path, socket_path);
unlink(socket_path); // Remove previous socket
bind(sockfd, (struct sockaddr*)&addr, sizeof(addr));
listen(sockfd, 5);
int client_fd = accept(sockfd, NULL, NULL);
char buffer[128];
read(client_fd, buffer, sizeof(buffer));
std::cout << "Server received: " << buffer << std::endl;
close(client_fd);
close(sockfd);
}
unlink(socket_path); // Clean up
return 0;
}