Fix a strict-alias warning in tst-inet6_rth.
[glibc.git] / manual / examples / mkfsock.c
blobe5c3b2847ff67b2dfbca2d73be581c9964d52546
1 /* Example of Local-Namespace Sockets
2 Copyright (C) 1991-2012 Free Software Foundation, Inc.
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.
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.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, if not, see <http://www.gnu.org/licenses/>.
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>
26 int
27 make_named_socket (const char *filename)
29 struct sockaddr_un name;
30 int sock;
31 size_t size;
33 /* Create the socket. */
34 sock = socket (PF_LOCAL, SOCK_DGRAM, 0);
35 if (sock < 0)
37 perror ("socket");
38 exit (EXIT_FAILURE);
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';
46 /* The size of the address is
47 the offset of the start of the filename,
48 plus its length,
49 plus one for the terminating null byte.
50 Alternatively you can just do:
51 size = SUN_LEN (&name);
53 size = (offsetof (struct sockaddr_un, sun_path)
54 + strlen (name.sun_path) + 1);
56 if (bind (sock, (struct sockaddr *) &name, size) < 0)
58 perror ("bind");
59 exit (EXIT_FAILURE);
62 return sock;