ba384ae36260a84815dd4edbfdc9cf22870787e2
[samba.git] / source / tests / unixsock.c
1 /*
2  * -*- c-file-style: "linux" -*-
3  *
4  * Try creating a Unix-domain socket, opening it, and reading from it.
5  * The POSIX name for these is AF_LOCAL/PF_LOCAL.
6  *
7  * This is used by the Samba autoconf scripts to detect systems which
8  * don't have Unix-domain sockets, such as (probably) VMS, or systems
9  * on which they are broken under some conditions, such as RedHat 7.0
10  * (unpatched).  We can't build WinBind there at the moment.
11  *
12  * Martin Pool <mbp@samba.org>, June 2000.
13  */
14
15 /* TODO: Look for AF_LOCAL (most standard), AF_UNIX, and AF_FILE. */
16
17 #include <stdio.h>
18
19 #if defined(HAVE_UNISTD_H)
20 #include <unistd.h>
21 #endif
22
23 #ifdef HAVE_SYS_SOCKET_H
24 #  include <sys/socket.h>
25 #endif
26
27 #ifdef HAVE_SYS_UN_H
28 #  include <sys/un.h>
29 #endif
30
31 #ifdef HAVE_SYS_TYPES_H
32 #  include <sys/types.h>
33 #endif
34
35 #if HAVE_SYS_WAIT_H
36 # include <sys/wait.h>
37 #endif
38
39 #if HAVE_ERRNO_DECL
40 # include <errno.h>
41 #else
42 extern int errno;
43 #endif
44
45 static int bind_socket(char const *filename)
46 {
47         int sock_fd;
48         struct sockaddr_un name;
49         size_t size;
50         
51         /* Create the socket. */
52         if ((sock_fd = socket(PF_LOCAL, SOCK_STREAM, 0)) < 0) {
53                 perror ("socket(PF_LOCAL, SOCK_STREAM)");
54                 return 1;
55         }
56      
57         /* Bind a name to the socket. */
58         name.sun_family = AF_LOCAL;
59         strncpy(name.sun_path, filename, sizeof (name.sun_path));
60      
61        /* The size of the address is
62           the offset of the start of the filename,
63           plus its length,
64           plus one for the terminating null byte.
65           Alternatively you can just do:
66           size = SUN_LEN (&name);
67       */
68         size = SUN_LEN(&name);
69         /* XXX: This probably won't work on unfriendly libcs */
70      
71         if (bind(sock_fd, (struct sockaddr *) &name, size) < 0) {
72                 perror ("bind");
73                 return 1;
74         }
75
76         return sock_fd;
77 }
78
79
80 int main(void)
81 {
82         int sock_fd;
83         int kid;
84         char const *filename = "conftest.unixsock.sock";
85
86         /* abolish hanging */
87         alarm(15);              /* secs */
88
89         if ((sock_fd = bind_socket(filename)) < 0)
90                 return 1;
91
92         /* the socket will be deleted when autoconf cleans up these
93            files. */
94
95         return 0;
96 }