]> git.ipfire.org Git - thirdparty/glibc.git/blame - manual/examples/mkfsock.c
Update copyright dates with scripts/update-copyrights
[thirdparty/glibc.git] / manual / examples / mkfsock.c
CommitLineData
d9a17c07 1/* Example of Local-Namespace Sockets
581c785b 2 Copyright (C) 1991-2022 Free Software Foundation, Inc.
d9a17c07
RM
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
5a82c748 15 along with this program; if not, see <https://www.gnu.org/licenses/>.
d9a17c07
RM
16*/
17
28f540f4
RM
18#include <stddef.h>
19#include <stdio.h>
20#include <errno.h>
21#include <stdlib.h>
bc15410e 22#include <string.h>
28f540f4
RM
23#include <sys/socket.h>
24#include <sys/un.h>
25
80aea676 26int
28f540f4
RM
27make_named_socket (const char *filename)
28{
29 struct sockaddr_un name;
30 int sock;
31 size_t size;
32
33 /* Create the socket. */
356d7100 34 sock = socket (PF_LOCAL, SOCK_DGRAM, 0);
28f540f4
RM
35 if (sock < 0)
36 {
37 perror ("socket");
38 exit (EXIT_FAILURE);
39 }
40
41 /* Bind a name to the socket. */
80aea676 42 name.sun_family = AF_LOCAL;
001426b8 43 strncpy (name.sun_path, filename, sizeof (name.sun_path));
654a7a0c 44 name.sun_path[sizeof (name.sun_path) - 1] = '\0';
28f540f4
RM
45
46 /* The size of the address is
47 the offset of the start of the filename,
550a0b89 48 plus its length (not including the terminating null byte).
49c091e5 49 Alternatively you can just do:
001426b8
UD
50 size = SUN_LEN (&name);
51 */
28f540f4 52 size = (offsetof (struct sockaddr_un, sun_path)
550a0b89 53 + strlen (name.sun_path));
28f540f4
RM
54
55 if (bind (sock, (struct sockaddr *) &name, size) < 0)
56 {
57 perror ("bind");
58 exit (EXIT_FAILURE);
59 }
60
61 return sock;
62}