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