1  /* Example of Local-Namespace Sockets from the glibc manual (16.5.3).  */
       2  
       3  #include <stddef.h>
       4  #include <stdio.h>
       5  #include <errno.h>
       6  #include <stdlib.h>
       7  #include <string.h>
       8  #include <sys/socket.h>
       9  #include <sys/un.h>
      10  
      11  int
      12  make_named_socket (const char *filename)
      13  {
      14    struct sockaddr_un name;
      15    int sock;
      16    size_t size;
      17  
      18    /* Create the socket. */
      19    sock = socket (PF_LOCAL, SOCK_DGRAM, 0);
      20    if (sock < 0)
      21      {
      22        perror ("socket");
      23        exit (EXIT_FAILURE);
      24      }
      25  
      26    /* Bind a name to the socket. */
      27    name.sun_family = AF_LOCAL;
      28    strncpy (name.sun_path, filename, sizeof (name.sun_path));
      29    name.sun_path[sizeof (name.sun_path) - 1] = '\0';
      30  
      31    /* The size of the address is
      32       the offset of the start of the filename,
      33       plus its length (not including the terminating null byte).
      34       Alternatively you can just do:
      35       size = SUN_LEN (&name);
      36   */
      37    size = (offsetof (struct sockaddr_un, sun_path)
      38            + strlen (name.sun_path));
      39  
      40    if (bind (sock, (struct sockaddr *) &name, size) < 0)
      41      {
      42        perror ("bind");
      43        exit (EXIT_FAILURE);
      44      }
      45  
      46    return sock;
      47  }