1/* Example of Local-Namespace Sockets
2 Copyright (C) 1991-2022 Free Software Foundation, Inc.
3
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, see <https://www.gnu.org/licenses/>.
16*/
17
18#include <stddef.h>
19#include <stdio.h>
20#include <errno.h>
21#include <stdlib.h>
22#include <string.h>
23#include <sys/socket.h>
24#include <sys/un.h>
25
26int
27make_named_socket (const char *filename)
28{
29 struct sockaddr_un name;
30 int sock;
31 size_t size;
32
33 /* Create the socket. */
34 sock = socket (PF_LOCAL, SOCK_DGRAM, protocol: 0);
35 if (sock < 0)
36 {
37 perror ("socket");
38 exit (EXIT_FAILURE);
39 }
40
41 /* Bind a name to the socket. */
42 name.sun_family = AF_LOCAL;
43 strncpy (name.sun_path, filename, sizeof (name.sun_path));
44 name.sun_path[sizeof (name.sun_path) - 1] = '\0';
45
46 /* The size of the address is
47 the offset of the start of the filename,
48 plus its length (not including the terminating null byte).
49 Alternatively you can just do:
50 size = SUN_LEN (&name);
51 */
52 size = (offsetof (struct sockaddr_un, sun_path)
53 + strlen (name.sun_path));
54
55 if (bind (fd: sock, addr: (struct sockaddr *) &name, len: size) < 0)
56 {
57 perror ("bind");
58 exit (EXIT_FAILURE);
59 }
60
61 return sock;
62}
63

source code of glibc/manual/examples/mkfsock.c