Analyzing the Unix Domain UDP Socket Code

The Unix Domain UDP socket code can be found here. The difference between a stream socket in the Unix domain and the UDP socket in the Unix domain is that in the UDP socket, the client and the server both connect to different socket files.

If we think of the stream socket as the server and the client being at the two ends of a pipe, then in the case of an UDP socket, we can think of the client sending a mail-post to the server and vice-versa. To send a post, the client and the server need to know the address of each other.

Let us now analyze the code in the previous article. The Server code opens a socket and binds to server socket path. The code snippets that achieve the same are provided below

        sock_fd = socket(AF_UNIX, SOCK_DGRAM, 0);

        remove(SOCK_PATH); /* SOCK_PATH = /tmp/unix_sock.sock */

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

Where “servaddr” is the socket the sockaddr_un UDP socket structure. The output of the “ss -xa shell command” for the server code after bind provides the below output

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

u_dgr   UNCONN   0             0              /tmp/unix_sock.sock 32334      * 0

The client code also binds to a particular socket path and it should also know the address of the server for it needs to send data to the server. The code snippets from the code example are provided below

        sockfd = socket(AF_UNIX, SOCK_DGRAM, 0);

        remove(SOCKPATH); /* SOCK_PATH = /tmp/unix_client_sock.sock */

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

        servaddr = (struct sockaddr_un *)malloc(sizeof(struct sockaddr_un));

        /* Address of the server SERVERPATH – /tmp/unix_sock.sock */

        snprintf(servaddr->sun_path, (strlen(SERVERPATH)+1), “%s”, SERVERPATH);

The output of the “ss -xa shell command” now shows a new socket connection for the client socket path. Note that the server and client are not connected to each other but have their respective socket file connections.

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

u_dgr   UNCONN    0           768      /tmp/unix_client_sock.sock 32420    * 0

Since the client specifically sends a packet to the serverpath given by /tmp/unix_sock.sock, packet reaches the server socket. The server socket can access the client address from the received packet (recvfrom API) and is able to respond back to the client.

The Connected UDP Socket Connection

Comments

  1. Pingback: Unix Domain UDP Socket Connection Example | Hitch Hiker's Guide to Learning

  2. 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 *