1UNIX(7) Linux Programmer's Manual UNIX(7)
2
3
4
6 unix - sockets for local interprocess communication
7
9 #include <sys/socket.h>
10 #include <sys/un.h>
11
12 unix_socket = socket(AF_UNIX, type, 0);
13 error = socketpair(AF_UNIX, type, 0, int *sv);
14
16 The AF_UNIX (also known as AF_LOCAL) socket family is used to communi‐
17 cate between processes on the same machine efficiently. Traditionally,
18 UNIX domain sockets can be either unnamed, or bound to a filesystem
19 pathname (marked as being of type socket). Linux also supports an
20 abstract namespace which is independent of the filesystem.
21
22 Valid socket types in the UNIX domain are: SOCK_STREAM, for a stream-
23 oriented socket; SOCK_DGRAM, for a datagram-oriented socket that pre‐
24 serves message boundaries (as on most UNIX implementations, UNIX domain
25 datagram sockets are always reliable and don't reorder datagrams); and
26 (since Linux 2.6.4) SOCK_SEQPACKET, for a sequenced-packet socket that
27 is connection-oriented, preserves message boundaries, and delivers mes‐
28 sages in the order that they were sent.
29
30 UNIX domain sockets support passing file descriptors or process creden‐
31 tials to other processes using ancillary data.
32
33 Address format
34 A UNIX domain socket address is represented in the following structure:
35
36 struct sockaddr_un {
37 sa_family_t sun_family; /* AF_UNIX */
38 char sun_path[108]; /* Pathname */
39 };
40
41 The sun_family field always contains AF_UNIX. On Linux, sun_path is
42 108 bytes in size; see also NOTES, below.
43
44 Various systems calls (for example, bind(2), connect(2), and sendto(2))
45 take a sockaddr_un argument as input. Some other system calls (for
46 example, getsockname(2), getpeername(2), recvfrom(2), and accept(2))
47 return an argument of this type.
48
49 Three types of address are distinguished in the sockaddr_un structure:
50
51 * pathname: a UNIX domain socket can be bound to a null-terminated
52 filesystem pathname using bind(2). When the address of a pathname
53 socket is returned (by one of the system calls noted above), its
54 length is
55
56 offsetof(struct sockaddr_un, sun_path) + strlen(sun_path) + 1
57
58 and sun_path contains the null-terminated pathname. (On Linux, the
59 above offsetof() expression equates to the same value as
60 sizeof(sa_family_t), but some other implementations include other
61 fields before sun_path, so the offsetof() expression more portably
62 describes the size of the address structure.)
63
64 For further details of pathname sockets, see below.
65
66 * unnamed: A stream socket that has not been bound to a pathname using
67 bind(2) has no name. Likewise, the two sockets created by socket‐
68 pair(2) are unnamed. When the address of an unnamed socket is
69 returned, its length is sizeof(sa_family_t), and sun_path should not
70 be inspected.
71
72 * abstract: an abstract socket address is distinguished (from a path‐
73 name socket) by the fact that sun_path[0] is a null byte ('\0').
74 The socket's address in this namespace is given by the additional
75 bytes in sun_path that are covered by the specified length of the
76 address structure. (Null bytes in the name have no special signifi‐
77 cance.) The name has no connection with filesystem pathnames. When
78 the address of an abstract socket is returned, the returned addrlen
79 is greater than sizeof(sa_family_t) (i.e., greater than 2), and the
80 name of the socket is contained in the first (addrlen -
81 sizeof(sa_family_t)) bytes of sun_path.
82
83 Pathname sockets
84 When binding a socket to a pathname, a few rules should be observed for
85 maximum portability and ease of coding:
86
87 * The pathname in sun_path should be null-terminated.
88
89 * The length of the pathname, including the terminating null byte,
90 should not exceed the size of sun_path.
91
92 * The addrlen argument that describes the enclosing sockaddr_un struc‐
93 ture should have a value of at least:
94
95 offsetof(struct sockaddr_un, sun_path)+strlen(addr.sun_path)+1
96
97 or, more simply, addrlen can be specified as sizeof(struct sock‐
98 addr_un).
99
100 There is some variation in how implementations handle UNIX domain
101 socket addresses that do not follow the above rules. For example, some
102 (but not all) implementations append a null terminator if none is
103 present in the supplied sun_path.
104
105 When coding portable applications, keep in mind that some implementa‐
106 tions have sun_path as short as 92 bytes.
107
108 Various system calls (accept(2), recvfrom(2), getsockname(2), getpeer‐
109 name(2)) return socket address structures. When applied to UNIX domain
110 sockets, the value-result addrlen argument supplied to the call should
111 be initialized as above. Upon return, the argument is set to indicate
112 the actual size of the address structure. The caller should check the
113 value returned in this argument: if the output value exceeds the input
114 value, then there is no guarantee that a null terminator is present in
115 sun_path. (See BUGS.)
116
117 Pathname socket ownership and permissions
118 In the Linux implementation, pathname sockets honor the permissions of
119 the directory they are in. Creation of a new socket fails if the
120 process does not have write and search (execute) permission on the
121 directory in which the socket is created.
122
123 On Linux, connecting to a stream socket object requires write permis‐
124 sion on that socket; sending a datagram to a datagram socket likewise
125 requires write permission on that socket. POSIX does not make any
126 statement about the effect of the permissions on a socket file, and on
127 some systems (e.g., older BSDs), the socket permissions are ignored.
128 Portable programs should not rely on this feature for security.
129
130 When creating a new socket, the owner and group of the socket file are
131 set according to the usual rules. The socket file has all permissions
132 enabled, other than those that are turned off by the process umask(2).
133
134 The owner, group, and permissions of a pathname socket can be changed
135 (using chown(2) and chmod(2)).
136
137 Abstract sockets
138 Socket permissions have no meaning for abstract sockets: the process
139 umask(2) has no effect when binding an abstract socket, and changing
140 the ownership and permissions of the object (via fchown(2) and fch‐
141 mod(2)) has no effect on the accessibility of the socket.
142
143 Abstract sockets automatically disappear when all open references to
144 the socket are closed.
145
146 The abstract socket namespace is a nonportable Linux extension.
147
148 Socket options
149 For historical reasons, these socket options are specified with a
150 SOL_SOCKET type even though they are AF_UNIX specific. They can be set
151 with setsockopt(2) and read with getsockopt(2) by specifying SOL_SOCKET
152 as the socket family.
153
154 SO_PASSCRED
155 Enabling this socket option causes receipt of the credentials of
156 the sending process in an SCM_CREDENTIALS ancillary message in
157 each subsequently received message. The returned credentials
158 are those specified by the sender using SCM_CREDENTIALS, or a
159 default that includes the sender's PID, real user ID, and real
160 group ID, if the sender did not specify SCM_CREDENTIALS ancil‐
161 lary data.
162
163 When this option is set and the socket is not yet connected, a
164 unique name in the abstract namespace will be generated automat‐
165 ically.
166
167 The value given as an argument to setsockopt(2) and returned as
168 the result of getsockopt(2) is an integer boolean flag.
169
170 SO_PASSSEC
171 Enables receiving of the SELinux security label of the peer
172 socket in an ancillary message of type SCM_SECURITY (see below).
173
174 The value given as an argument to setsockopt(2) and returned as
175 the result of getsockopt(2) is an integer boolean flag.
176
177 The SO_PASSSEC option is supported for UNIX domain datagram
178 sockets since Linux 2.6.18; support for UNIX domain stream sock‐
179 ets was added in Linux 4.2.
180
181 SO_PEEK_OFF
182 See socket(7).
183
184 SO_PEERCRED
185 This read-only socket option returns the credentials of the peer
186 process connected to this socket. The returned credentials are
187 those that were in effect at the time of the call to connect(2)
188 or socketpair(2).
189
190 The argument to getsockopt(2) is a pointer to a ucred structure;
191 define the _GNU_SOURCE feature test macro to obtain the defini‐
192 tion of that structure from <sys/socket.h>.
193
194 The use of this option is possible only for connected AF_UNIX
195 stream sockets and for AF_UNIX stream and datagram socket pairs
196 created using socketpair(2).
197
198 Autobind feature
199 If a bind(2) call specifies addrlen as sizeof(sa_family_t), or the
200 SO_PASSCRED socket option was specified for a socket that was not
201 explicitly bound to an address, then the socket is autobound to an
202 abstract address. The address consists of a null byte followed by 5
203 bytes in the character set [0-9a-f]. Thus, there is a limit of 2^20
204 autobind addresses. (From Linux 2.1.15, when the autobind feature was
205 added, 8 bytes were used, and the limit was thus 2^32 autobind
206 addresses. The change to 5 bytes came in Linux 2.3.15.)
207
208 Sockets API
209 The following paragraphs describe domain-specific details and unsup‐
210 ported features of the sockets API for UNIX domain sockets on Linux.
211
212 UNIX domain sockets do not support the transmission of out-of-band data
213 (the MSG_OOB flag for send(2) and recv(2)).
214
215 The send(2) MSG_MORE flag is not supported by UNIX domain sockets.
216
217 Before Linux 3.4, the use of MSG_TRUNC in the flags argument of recv(2)
218 was not supported by UNIX domain sockets.
219
220 The SO_SNDBUF socket option does have an effect for UNIX domain sock‐
221 ets, but the SO_RCVBUF option does not. For datagram sockets, the
222 SO_SNDBUF value imposes an upper limit on the size of outgoing data‐
223 grams. This limit is calculated as the doubled (see socket(7)) option
224 value less 32 bytes used for overhead.
225
226 Ancillary messages
227 Ancillary data is sent and received using sendmsg(2) and recvmsg(2).
228 For historical reasons, the ancillary message types listed below are
229 specified with a SOL_SOCKET type even though they are AF_UNIX specific.
230 To send them, set the cmsg_level field of the struct cmsghdr to
231 SOL_SOCKET and the cmsg_type field to the type. For more information,
232 see cmsg(3).
233
234 SCM_RIGHTS
235 Send or receive a set of open file descriptors from another
236 process. The data portion contains an integer array of the file
237 descriptors.
238
239 Commonly, this operation is referred to as "passing a file
240 descriptor" to another process. However, more accurately, what
241 is being passed is a reference to an open file description (see
242 open(2)), and in the receiving process it is likely that a dif‐
243 ferent file descriptor number will be used. Semantically, this
244 operation is equivalent to duplicating (dup(2)) a file descrip‐
245 tor into the file descriptor table of another process.
246
247 If the buffer used to receive the ancillary data containing file
248 descriptors is too small (or is absent), then the ancillary data
249 is truncated (or discarded) and the excess file descriptors are
250 automatically closed in the receiving process.
251
252 If the number of file descriptors received in the ancillary data
253 would cause the process to exceed its RLIMIT_NOFILE resource
254 limit (see getrlimit(2)), the excess file descriptors are auto‐
255 matically closed in the receiving process.
256
257 The kernel constant SCM_MAX_FD defines a limit on the number of
258 file descriptors in the array. Attempting to send an array
259 larger than this limit causes sendmsg(2) to fail with the error
260 EINVAL. SCM_MAX_FD has the value 253 (or 255 in kernels before
261 2.6.38).
262
263 SCM_CREDENTIALS
264 Send or receive UNIX credentials. This can be used for authen‐
265 tication. The credentials are passed as a struct ucred ancil‐
266 lary message. Thus structure is defined in <sys/socket.h> as
267 follows:
268
269 struct ucred {
270 pid_t pid; /* Process ID of the sending process */
271 uid_t uid; /* User ID of the sending process */
272 gid_t gid; /* Group ID of the sending process */
273 };
274
275 Since glibc 2.8, the _GNU_SOURCE feature test macro must be
276 defined (before including any header files) in order to obtain
277 the definition of this structure.
278
279 The credentials which the sender specifies are checked by the
280 kernel. A privileged process is allowed to specify values that
281 do not match its own. The sender must specify its own process
282 ID (unless it has the capability CAP_SYS_ADMIN), its real user
283 ID, effective user ID, or saved set-user-ID (unless it has
284 CAP_SETUID), and its real group ID, effective group ID, or saved
285 set-group-ID (unless it has CAP_SETGID).
286
287 To receive a struct ucred message, the SO_PASSCRED option must
288 be enabled on the socket.
289
290 SCM_SECURITY
291 Receive the SELinux security context (the security label) of the
292 peer socket. The received ancillary data is a null-terminated
293 string containing the security context. The receiver should
294 allocate at least NAME_MAX bytes in the data portion of the
295 ancillary message for this data.
296
297 To receive the security context, the SO_PASSSEC option must be
298 enabled on the socket (see above).
299
300 When sending ancillary data with sendmsg(2), only one item of each of
301 the above types may be included in the sent message.
302
303 At least one byte of real data should be sent when sending ancillary
304 data. On Linux, this is required to successfully send ancillary data
305 over a UNIX domain stream socket. When sending ancillary data over a
306 UNIX domain datagram socket, it is not necessary on Linux to send any
307 accompanying real data. However, portable applications should also
308 include at least one byte of real data when sending ancillary data over
309 a datagram socket.
310
311 When receiving from a stream socket, ancillary data forms a kind of
312 barrier for the received data. For example, suppose that the sender
313 transmits as follows:
314
315 1. sendmsg(2) of four bytes, with no ancillary data.
316 2. sendmsg(2) of one byte, with ancillary data.
317 3. sendmsg(2) of four bytes, with no ancillary data.
318
319 Suppose that the receiver now performs recvmsg(2) calls each with a
320 buffer size of 20 bytes. The first call will receive five bytes of
321 data, along with the ancillary data sent by the second sendmsg(2) call.
322 The next call will receive the remaining five bytes of data.
323
324 If the space allocated for receiving incoming ancillary data is too
325 small then the ancillary data is truncated to the number of headers
326 that will fit in the supplied buffer (or, in the case of an SCM_RIGHTS
327 file descriptor list, the list of file descriptors may be truncated).
328 If no buffer is provided for incoming ancillary data (i.e., the
329 msg_control field of the msghdr structure supplied to recvmsg(2) is
330 NULL), then the incoming ancillary data is discarded. In both of these
331 cases, the MSG_CTRUNC flag will be set in the msg.msg_flags value
332 returned by recvmsg(2).
333
334 Ioctls
335 The following ioctl(2) calls return information in value. The correct
336 syntax is:
337
338 int value;
339 error = ioctl(unix_socket, ioctl_type, &value);
340
341 ioctl_type can be:
342
343 SIOCINQ
344 For SOCK_STREAM sockets, this call returns the number of unread
345 bytes in the receive buffer. The socket must not be in LISTEN
346 state, otherwise an error (EINVAL) is returned. SIOCINQ is
347 defined in <linux/sockios.h>. Alternatively, you can use the
348 synonymous FIONREAD, defined in <sys/ioctl.h>. For SOCK_DGRAM
349 sockets, the returned value is the same as for Internet domain
350 datagram sockets; see udp(7).
351
353 EADDRINUSE
354 The specified local address is already in use or the filesystem
355 socket object already exists.
356
357 EBADF This error can occur for sendmsg(2) when sending a file descrip‐
358 tor as ancillary data over a UNIX domain socket (see the
359 description of SCM_RIGHTS, above), and indicates that the file
360 descriptor number that is being sent is not valid (e.g., it is
361 not an open file descriptor).
362
363 ECONNREFUSED
364 The remote address specified by connect(2) was not a listening
365 socket. This error can also occur if the target pathname is not
366 a socket.
367
368 ECONNRESET
369 Remote socket was unexpectedly closed.
370
371 EFAULT User memory address was not valid.
372
373 EINVAL Invalid argument passed. A common cause is that the value
374 AF_UNIX was not specified in the sun_type field of passed
375 addresses, or the socket was in an invalid state for the applied
376 operation.
377
378 EISCONN
379 connect(2) called on an already connected socket or a target
380 address was specified on a connected socket.
381
382 ENOENT The pathname in the remote address specified to connect(2) did
383 not exist.
384
385 ENOMEM Out of memory.
386
387 ENOTCONN
388 Socket operation needs a target address, but the socket is not
389 connected.
390
391 EOPNOTSUPP
392 Stream operation called on non-stream oriented socket or tried
393 to use the out-of-band data option.
394
395 EPERM The sender passed invalid credentials in the struct ucred.
396
397 EPIPE Remote socket was closed on a stream socket. If enabled, a SIG‐
398 PIPE is sent as well. This can be avoided by passing the
399 MSG_NOSIGNAL flag to send(2) or sendmsg(2).
400
401 EPROTONOSUPPORT
402 Passed protocol is not AF_UNIX.
403
404 EPROTOTYPE
405 Remote socket does not match the local socket type (SOCK_DGRAM
406 versus SOCK_STREAM).
407
408 ESOCKTNOSUPPORT
409 Unknown socket type.
410
411 ETOOMANYREFS
412 This error can occur for sendmsg(2) when sending a file descrip‐
413 tor as ancillary data over a UNIX domain socket (see the
414 description of SCM_RIGHTS, above). It occurs if the number of
415 "in-flight" file descriptors exceeds the RLIMIT_NOFILE resource
416 limit and the caller does not have the CAP_SYS_RESOURCE capabil‐
417 ity. An in-flight file descriptor is one that has been sent
418 using sendmsg(2) but has not yet been accepted in the recipient
419 process using recvmsg(2).
420
421 This error is diagnosed since mainline Linux 4.5 (and in some
422 earlier kernel versions where the fix has been backported). In
423 earlier kernel versions, it was possible to place an unlimited
424 number of file descriptors in flight, by sending each file
425 descriptor with sendmsg(2) and then closing the file descriptor
426 so that it was not accounted against the RLIMIT_NOFILE resource
427 limit.
428
429 Other errors can be generated by the generic socket layer or by the
430 filesystem while generating a filesystem socket object. See the appro‐
431 priate manual pages for more information.
432
434 SCM_CREDENTIALS and the abstract namespace were introduced with Linux
435 2.2 and should not be used in portable programs. (Some BSD-derived
436 systems also support credential passing, but the implementation details
437 differ.)
438
440 Binding to a socket with a filename creates a socket in the filesystem
441 that must be deleted by the caller when it is no longer needed (using
442 unlink(2)). The usual UNIX close-behind semantics apply; the socket
443 can be unlinked at any time and will be finally removed from the
444 filesystem when the last reference to it is closed.
445
446 To pass file descriptors or credentials over a SOCK_STREAM socket, you
447 must to send or receive at least one byte of nonancillary data in the
448 same sendmsg(2) or recvmsg(2) call.
449
450 UNIX domain stream sockets do not support the notion of out-of-band
451 data.
452
454 When binding a socket to an address, Linux is one of the implementa‐
455 tions that appends a null terminator if none is supplied in sun_path.
456 In most cases this is unproblematic: when the socket address is
457 retrieved, it will be one byte longer than that supplied when the
458 socket was bound. However, there is one case where confusing behavior
459 can result: if 108 non-null bytes are supplied when a socket is bound,
460 then the addition of the null terminator takes the length of the path‐
461 name beyond sizeof(sun_path). Consequently, when retrieving the socket
462 address (for example, via accept(2)), if the input addrlen argument for
463 the retrieving call is specified as sizeof(struct sockaddr_un), then
464 the returned address structure won't have a null terminator in
465 sun_path.
466
467 In addition, some implementations don't require a null terminator when
468 binding a socket (the addrlen argument is used to determine the length
469 of sun_path) and when the socket address is retrieved on these imple‐
470 mentations, there is no null terminator in sun_path.
471
472 Applications that retrieve socket addresses can (portably) code to han‐
473 dle the possibility that there is no null terminator in sun_path by
474 respecting the fact that the number of valid bytes in the pathname is:
475
476 strnlen(addr.sun_path, addrlen - offsetof(sockaddr_un, sun_path))
477
478 Alternatively, an application can retrieve the socket address by allo‐
479 cating a buffer of size sizeof(struct sockaddr_un)+1 that is zeroed out
480 before the retrieval. The retrieving call can specify addrlen as
481 sizeof(struct sockaddr_un), and the extra zero byte ensures that there
482 will be a null terminator for the string returned in sun_path:
483
484 void *addrp;
485
486 addrlen = sizeof(struct sockaddr_un);
487 addrp = malloc(addrlen + 1);
488 if (addrp == NULL)
489 /* Handle error */ ;
490 memset(addrp, 0, addrlen + 1);
491
492 if (getsockname(sfd, (struct sockaddr *) addrp, &addrlen)) == -1)
493 /* handle error */ ;
494
495 printf("sun_path = %s\n", ((struct sockaddr_un *) addrp)->sun_path);
496
497 This sort of messiness can be avoided if it is guaranteed that the
498 applications that create pathname sockets follow the rules outlined
499 above under Pathname sockets.
500
502 The following code demonstrates the use of sequenced-packet sockets for
503 local interprocess communication. It consists of two programs. The
504 server program waits for a connection from the client program. The
505 client sends each of its command-line arguments in separate messages.
506 The server treats the incoming messages as integers and adds them up.
507 The client sends the command string "END". The server sends back a
508 message containing the sum of the client's integers. The client prints
509 the sum and exits. The server waits for the next client to connect.
510 To stop the server, the client is called with the command-line argument
511 "DOWN".
512
513 The following output was recorded while running the server in the back‐
514 ground and repeatedly executing the client. Execution of the server
515 program ends when it receives the "DOWN" command.
516
517 Example output
518 $ ./server &
519 [1] 25887
520 $ ./client 3 4
521 Result = 7
522 $ ./client 11 -5
523 Result = 6
524 $ ./client DOWN
525 Result = 0
526 [1]+ Done ./server
527 $
528
529 Program source
530
531 /*
532 * File connection.h
533 */
534
535 #define SOCKET_NAME "/tmp/9Lq7BNBnBycd6nxy.socket"
536 #define BUFFER_SIZE 12
537
538 /*
539 * File server.c
540 */
541
542 #include <stdio.h>
543 #include <stdlib.h>
544 #include <string.h>
545 #include <sys/socket.h>
546 #include <sys/un.h>
547 #include <unistd.h>
548 #include "connection.h"
549
550 int
551 main(int argc, char *argv[])
552 {
553 struct sockaddr_un name;
554 int down_flag = 0;
555 int ret;
556 int connection_socket;
557 int data_socket;
558 int result;
559 char buffer[BUFFER_SIZE];
560
561 /*
562 * In case the program exited inadvertently on the last run,
563 * remove the socket.
564 */
565
566 unlink(SOCKET_NAME);
567
568 /* Create local socket. */
569
570 connection_socket = socket(AF_UNIX, SOCK_SEQPACKET, 0);
571 if (connection_socket == -1) {
572 perror("socket");
573 exit(EXIT_FAILURE);
574 }
575
576 /*
577 * For portability clear the whole structure, since some
578 * implementations have additional (nonstandard) fields in
579 * the structure.
580 */
581
582 memset(&name, 0, sizeof(struct sockaddr_un));
583
584 /* Bind socket to socket name. */
585
586 name.sun_family = AF_UNIX;
587 strncpy(name.sun_path, SOCKET_NAME, sizeof(name.sun_path) - 1);
588
589 ret = bind(connection_socket, (const struct sockaddr *) &name,
590 sizeof(struct sockaddr_un));
591 if (ret == -1) {
592 perror("bind");
593 exit(EXIT_FAILURE);
594 }
595
596 /*
597 * Prepare for accepting connections. The backlog size is set
598 * to 20. So while one request is being processed other requests
599 * can be waiting.
600 */
601
602 ret = listen(connection_socket, 20);
603 if (ret == -1) {
604 perror("listen");
605 exit(EXIT_FAILURE);
606 }
607
608 /* This is the main loop for handling connections. */
609
610 for (;;) {
611
612 /* Wait for incoming connection. */
613
614 data_socket = accept(connection_socket, NULL, NULL);
615 if (data_socket == -1) {
616 perror("accept");
617 exit(EXIT_FAILURE);
618 }
619
620 result = 0;
621 for (;;) {
622
623 /* Wait for next data packet. */
624
625 ret = read(data_socket, buffer, BUFFER_SIZE);
626 if (ret == -1) {
627 perror("read");
628 exit(EXIT_FAILURE);
629 }
630
631 /* Ensure buffer is 0-terminated. */
632
633 buffer[BUFFER_SIZE - 1] = 0;
634
635 /* Handle commands. */
636
637 if (!strncmp(buffer, "DOWN", BUFFER_SIZE)) {
638 down_flag = 1;
639 break;
640 }
641
642 if (!strncmp(buffer, "END", BUFFER_SIZE)) {
643 break;
644 }
645
646 /* Add received summand. */
647
648 result += atoi(buffer);
649 }
650
651 /* Send result. */
652
653 sprintf(buffer, "%d", result);
654 ret = write(data_socket, buffer, BUFFER_SIZE);
655 if (ret == -1) {
656 perror("write");
657 exit(EXIT_FAILURE);
658 }
659
660 /* Close socket. */
661
662 close(data_socket);
663
664 /* Quit on DOWN command. */
665
666 if (down_flag) {
667 break;
668 }
669 }
670
671 close(connection_socket);
672
673 /* Unlink the socket. */
674
675 unlink(SOCKET_NAME);
676
677 exit(EXIT_SUCCESS);
678 }
679
680 /*
681 * File client.c
682 */
683
684 #include <errno.h>
685 #include <stdio.h>
686 #include <stdlib.h>
687 #include <string.h>
688 #include <sys/socket.h>
689 #include <sys/un.h>
690 #include <unistd.h>
691 #include "connection.h"
692
693 int
694 main(int argc, char *argv[])
695 {
696 struct sockaddr_un addr;
697 int i;
698 int ret;
699 int data_socket;
700 char buffer[BUFFER_SIZE];
701
702 /* Create local socket. */
703
704 data_socket = socket(AF_UNIX, SOCK_SEQPACKET, 0);
705 if (data_socket == -1) {
706 perror("socket");
707 exit(EXIT_FAILURE);
708 }
709
710 /*
711 * For portability clear the whole structure, since some
712 * implementations have additional (nonstandard) fields in
713 * the structure.
714 */
715
716 memset(&addr, 0, sizeof(struct sockaddr_un));
717
718 /* Connect socket to socket address */
719
720 addr.sun_family = AF_UNIX;
721 strncpy(addr.sun_path, SOCKET_NAME, sizeof(addr.sun_path) - 1);
722
723 ret = connect (data_socket, (const struct sockaddr *) &addr,
724 sizeof(struct sockaddr_un));
725 if (ret == -1) {
726 fprintf(stderr, "The server is down.\n");
727 exit(EXIT_FAILURE);
728 }
729
730 /* Send arguments. */
731
732 for (i = 1; i < argc; ++i) {
733 ret = write(data_socket, argv[i], strlen(argv[i]) + 1);
734 if (ret == -1) {
735 perror("write");
736 break;
737 }
738 }
739
740 /* Request result. */
741
742 strcpy (buffer, "END");
743 ret = write(data_socket, buffer, strlen(buffer) + 1);
744 if (ret == -1) {
745 perror("write");
746 exit(EXIT_FAILURE);
747 }
748
749 /* Receive result. */
750
751 ret = read(data_socket, buffer, BUFFER_SIZE);
752 if (ret == -1) {
753 perror("read");
754 exit(EXIT_FAILURE);
755 }
756
757 /* Ensure buffer is 0-terminated. */
758
759 buffer[BUFFER_SIZE - 1] = 0;
760
761 printf("Result = %s\n", buffer);
762
763 /* Close socket. */
764
765 close(data_socket);
766
767 exit(EXIT_SUCCESS);
768 }
769
770 For an example of the use of SCM_RIGHTS see cmsg(3).
771
773 recvmsg(2), sendmsg(2), socket(2), socketpair(2), cmsg(3), capabili‐
774 ties(7), credentials(7), socket(7), udp(7)
775
777 This page is part of release 5.02 of the Linux man-pages project. A
778 description of the project, information about reporting bugs, and the
779 latest version of this page, can be found at
780 https://www.kernel.org/doc/man-pages/.
781
782
783
784Linux 2019-08-02 UNIX(7)