Update.
[glibc.git] / manual / examples / mkfsock.c
blobaffeba66bec19685063d946a8bfba4a195071e68
1 #include <stddef.h>
2 #include <stdio.h>
3 #include <errno.h>
4 #include <stdlib.h>
5 #include <sys/socket.h>
6 #include <sys/un.h>
8 int
9 make_named_socket (const char *filename)
11 struct sockaddr_un name;
12 int sock;
13 size_t size;
15 /* Create the socket. */
16 sock = socket (PF_LOCAL, SOCK_DGRAM, 0);
17 if (sock < 0)
19 perror ("socket");
20 exit (EXIT_FAILURE);
23 /* Bind a name to the socket. */
24 name.sun_family = AF_LOCAL;
25 strncpy (name.sun_path, filename, sizeof (name.sun_path));
27 /* The size of the address is
28 the offset of the start of the filename,
29 plus its length,
30 plus one for the terminating null byte.
31 Alternatively you can just do:
32 size = SUN_LEN (&name);
34 size = (offsetof (struct sockaddr_un, sun_path)
35 + strlen (name.sun_path) + 1);
37 if (bind (sock, (struct sockaddr *) &name, size) < 0)
39 perror ("bind");
40 exit (EXIT_FAILURE);
43 return sock;