Linux / Unix - Sockets
Last Updated: 2023-02-05
Unix Domain Sockets vs Internet Domain Sockets
- Unix Domain Sockets: a.k.a. IPC sockets, allow communication between 2 processes on the same machine.
- use the file system as the address space (everything in Unix is a file) e.g.
/var/run/docker/containerd/containerd.sock
- use the file system as the address space (everything in Unix is a file) e.g.
- Internet Domain Sockets: allow communication over a network.
- use the IP address and a port number as socket address, e.g.
10.20.30.40:4444
;
- use the IP address and a port number as socket address, e.g.
As you can see from the system call below, they are distinguished by the domain
.
System Calls
int socket(int domain, int type, int protocol);
Most important domain
s:
AF_INET
: IPv4AF_INET6
: IPv6AF_UNIX
/AF_LOCAL
: Unix Socket
Most common type
s:
SOCK_STREAM
: a stream-oriented socket (TCP)SOCK_DGRAM
: a datagram-oriented socket (UDP)
protocol
: specify the protocol. In most cases there's only one protocol for the specified type, use 0
for protocol
.
Example:
fd = socket(AF_UNIX, SOCK_STREAM, 0);
After we create the sockets on both server and client sides:
- Server side:
- use
bind()
system call to bind it to an address. - use
listen()
system call to mark the socket as passive. (by default, the socket is active) - use
accept()
system call to accept an incoming connection.
- use
- Client side:
- use
connect()
system call to connect to a passive socket, using the same address.
- use
Then use read()
and write()
system calls to communicate with the peer socket.
Remember to call close()
to close the sockets.
Commands
ss
ss
: get all connectionsss -t
: get tcp connections not in listen mode (server programs)ss -u
: get udp connections not in listen modess -x
: get unix socket pipe connectionsss -ta
: get all tcp connectionsss -au
: get all udp connectionsss -nt
: all tcp without host namess -ltn
: listening tcp without host resolutionss -ltp
: listening tcp with PID and namess -s
: prints statsticsss -tn -o
: tcp connection with domain host and show keepalive timerss -tl4
: ip4 connections
ss vs netstat:
netstat
: read various/proc
files to gather information. Slow when there are lots of connections to display. Now deprecated.ss
: get information directly from kernel space.