The code for an Abstract Namespace Unix domain (AF_UNIX) socket is provided at the link here. As can be seen in the server and client code, the steps to connect to the stream socket all remain the same on the server and the client side relative to any other stream socket connection.
The difference in the implementation of an AF_UNIX stream socket code and the AF_UNIX abstract namespace code is in the removal of the filesystem path for the socket to bind to.
The socket path does not have a file-system entry like “/tmp/unix_socket.sock” as was seen in the AF_UNIX stream socket code implementation and takes a null file system path.
The first byte of the socket path is appended with a ‘\0‘ byte indicating a null file-system path and the null path is understood by the operating system to recognize the socket as an abstract path and act accordingly.
The socket connections maintained by the operating system which are of abstract namespace type usually have a “@” symbol in the “ss shell command” output. we shall see that later.
From the socket code example, we see that the server side code, creates a socket, binds to the socket with the abstract path and converts to a passive socket via listen API and waits for incoming client connections via accept API. code snippets from the example are posted below
sockserver = socket(AF_UNIX, SOCK_STREAM, 0);
/* path is set to #unix_socket.sock */
snprintf(servaddr->sun_path, (strlen(path)+1), ā%sā, path);
servaddr->sun_path[0] = ‘\0’;
bind(sockserver,(struct sockaddr *)servaddr, sizeof(struct sockaddr_un));
listen(sockserver, 1);
accept(sockserver, (struct sockaddr *)cliaddr, &length);
The output of the “ss -x -a” shell command indicates the server socket to be in listen mode waiting for connections. Notice the name of the socket path in the “ss shell command” output. It has “@” symbol instead of a file system path.
Netid State Recv-Q Send-Q Local Address:Port Peer Address:Port
u_str LISTEN 0 1 @unix_socket.sock@@@@@@ 32089 * 0
The client code opens a socket and connects to the same server socket. Code snippets from the sample code is provided below
sockserver = socket(AF_UNIX, SOCK_STREAM, 0);
snprintf(servaddr->sun_path, (strlen(path)+1), “%s”, path);
servaddr->sun_path[0] = ‘\0’;
connect(sockserver, (struct sockaddr *)servaddr, sizeof(struct sockaddr_un))
once the connection to the server is completed, data transaction between the client and the server can occur via send/recv APIs.
The output for the server/client socket connection is shown in the output of the “ss -x -a” shell command.
Netid State Recv-Q Send-Q Local Address:Port Peer Address:Port
u_str ESTAB 50 0 @unix_socket.sock@@@@@@ 32090 * 33393
The next article provides for an abstract namespace datagram socket.
Pingback: Abstract Namespace AF_UNIX stream socket code example | Hitch Hiker's Guide to Learning