Analyzing the AF_UNIX Abstract Namespace Datagram socket code example

The code for the AF_UNIX Abstract Namespace datagram socket code example can be found at this link.

The APIs and the connection steps are the same for the code as a AF_UNIX UDP socket connection code. The difference is that the socket path is an abstract path. 

code snippets from the server code to create the socket, the abstract path and the bind API for the server are provided below

        sock_fd = socket(AF_UNIX, SOCK_DGRAM, 0);

       /* path is – #unix_sock.sock – \0 is appended at # */

        servaddr->sun_family = AF_UNIX;
        snprintf(servaddr->sun_path, (strlen(SOCK_PATH)+1), “%s”, SOCK_PATH);
        servaddr->sun_path[0] = ‘\0’;

        bind(sock_fd, (struct sockaddr *)servaddr, sizeof(struct sockaddr_un));

once the server binds to the socket, it awaits the client code to send packet data to it. Once a packet is received by the server, it can respond back to the client via the address gleaned from the recvfrom API.

The “ss” shell command API output for the server is shown below

Netid    State        Recv-Q    Send-Q     Local Address:Port                                Peer Address:Port

u_dgr   UNCONN    0            0                @unix_sock.sock@@@@@@ 32010           * 0

The client code performs similar steps to the server code and creates a socket and binds to its own socket path and sends a data packet to the server. The client needs to be aware of the server path to send packet to. The code snippets from the sample program are shown below.

        sockfd = socket(AF_UNIX, SOCK_DGRAM, 0);

        /* path – #unix_client_sock.sock – # is replaced with \0 */

        clientaddr->sun_family = AF_UNIX;
        snprintf(clientaddr->sun_path, (strlen(SOCKPATH)+1), “%s”, SOCKPATH);
       clientaddr->sun_path[0] = ‘\0’;

        bind(sockfd, (struct sockaddr*)clientaddr, sizeof(struct sockaddr_un));

        /* server path is path of the server – #unix_sock.sock */

        servaddr->sun_family = AF_UNIX;
        snprintf(servaddr->sun_path, (strlen(SERVERPATH)+1), “%s”, SERVERPATH);
        servaddr->sun_path[0] = ‘\0’;

The output of the “ss” shell command for the client code is provided below. Once data is sent to the server, both the server and the client can send data to one another.

Netid    State        Recv-Q   Send-Q   Local Address:Port                                         Peer Address:Port

u_dgr   UNCONN  50           0            @unix_client_sock.sock@@@@@@ 30190       * 0

SocketPair socket connection

Comments

  1. Pingback: The Abstract Namespace AF_UNIX Datagram Socket code example | Hitch Hiker's Guide to Learning

Leave a Reply

Your email address will not be published. Required fields are marked *