2.9
[glibc/nacl-glibc.git] / manual / examples / mkfsock.c
blob615ecd8684087a70406bf682e76eaa655385caa0
1 #include <stddef.h>
2 #include <stdio.h>
3 #include <errno.h>
4 #include <stdlib.h>
5 #include <string.h>
6 #include <sys/socket.h>
7 #include <sys/un.h>
9 int
10 make_named_socket (const char *filename)
12 struct sockaddr_un name;
13 int sock;
14 size_t size;
16 /* Create the socket. */
17 sock = socket (PF_LOCAL, SOCK_DGRAM, 0);
18 if (sock < 0)
20 perror ("socket");
21 exit (EXIT_FAILURE);
24 /* Bind a name to the socket. */
25 name.sun_family = AF_LOCAL;
26 strncpy (name.sun_path, filename, sizeof (name.sun_path));
27 name.sun_path[sizeof (name.sun_path) - 1] = '\0';
29 /* The size of the address is
30 the offset of the start of the filename,
31 plus its length,
32 plus one for the terminating null byte.
33 Alternatively you can just do:
34 size = SUN_LEN (&name);
36 size = (offsetof (struct sockaddr_un, sun_path)
37 + strlen (name.sun_path) + 1);
39 if (bind (sock, (struct sockaddr *) &name, size) < 0)
41 perror ("bind");
42 exit (EXIT_FAILURE);
45 return sock;