Back to index

glibc  2.9
mkfsock.c
Go to the documentation of this file.
00001 #include <stddef.h>
00002 #include <stdio.h>
00003 #include <errno.h>
00004 #include <stdlib.h>
00005 #include <string.h>
00006 #include <sys/socket.h>
00007 #include <sys/un.h>
00008 
00009 int
00010 make_named_socket (const char *filename)
00011 {
00012   struct sockaddr_un name;
00013   int sock;
00014   size_t size;
00015 
00016   /* Create the socket.  */
00017   sock = socket (PF_LOCAL, SOCK_DGRAM, 0);
00018   if (sock < 0)
00019     {
00020       perror ("socket");
00021       exit (EXIT_FAILURE);
00022     }
00023 
00024   /* Bind a name to the socket.  */
00025   name.sun_family = AF_LOCAL;
00026   strncpy (name.sun_path, filename, sizeof (name.sun_path));
00027   name.sun_path[sizeof (name.sun_path) - 1] = '\0';
00028 
00029   /* The size of the address is
00030      the offset of the start of the filename,
00031      plus its length,
00032      plus one for the terminating null byte.
00033      Alternatively you can just do:
00034      size = SUN_LEN (&name);
00035   */
00036   size = (offsetof (struct sockaddr_un, sun_path)
00037          + strlen (name.sun_path) + 1);
00038 
00039   if (bind (sock, (struct sockaddr *) &name, size) < 0)
00040     {
00041       perror ("bind");
00042       exit (EXIT_FAILURE);
00043     }
00044 
00045   return sock;
00046 }