1 .\" This man page is Copyright (C) 1999 Andi Kleen <ak@muc.de>,
2 .\" Copyright (C) 2008-2014, Michael Kerrisk <mtk.manpages@gmail.com>,
3 .\" and Copyright (C) 2016, Heinrich Schuchardt <xypron.glpk@gmx.de>
5 .\" %%%LICENSE_START(VERBATIM_ONE_PARA)
6 .\" Permission is granted to distribute possibly modified copies
7 .\" of this page provided the header is included verbatim,
8 .\" and in case of nontrivial modification author and date
9 .\" of the modification is added to the header.
12 .\" Modified, 2003-12-02, Michael Kerrisk, <mtk.manpages@gmail.com>
13 .\" Modified, 2003-09-23, Adam Langley
14 .\" Modified, 2004-05-27, Michael Kerrisk, <mtk.manpages@gmail.com>
15 .\" Added SOCK_SEQPACKET
16 .\" 2008-05-27, mtk, Provide a clear description of the three types of
17 .\" address that can appear in the sockaddr_un structure: pathname,
18 .\" unnamed, and abstract.
20 .TH UNIX 7 2016-07-17 "Linux" "Linux Programmer's Manual"
22 unix \- sockets for local interprocess communication
24 .B #include <sys/socket.h>
26 .B #include <sys/un.h>
28 .IB unix_socket " = socket(AF_UNIX, type, 0);"
30 .IB error " = socketpair(AF_UNIX, type, 0, int *" sv ");"
36 socket family is used to communicate between processes on the same machine
38 Traditionally, UNIX domain sockets can be either unnamed,
39 or bound to a filesystem pathname (marked as being of type socket).
40 Linux also supports an abstract namespace which is independent of the
43 Valid socket types in the UNIX domain are:
45 for a stream-oriented socket;
47 for a datagram-oriented socket that preserves message boundaries
48 (as on most UNIX implementations, UNIX domain datagram
49 sockets are always reliable and don't reorder datagrams);
50 and (since Linux 2.6.4)
52 for a sequenced-packet socket that is connection-oriented,
53 preserves message boundaries,
54 and delivers messages in the order that they were sent.
56 UNIX domain sockets support passing file descriptors or process credentials
57 to other processes using ancillary data.
59 A UNIX domain socket address is represented in the following structure:
63 .\" #define UNIX_PATH_MAX 108
66 sa_family_t sun_family; /* AF_UNIX */
67 char sun_path[108]; /* pathname */
78 is 108 bytes in size; see also NOTES, below.
80 Various systems calls (for example,
88 Some other system calls (for example,
94 return an argument of this type.
96 Three types of address are distinguished in the
101 a UNIX domain socket can be bound to a null-terminated
102 filesystem pathname using
104 When the address of a pathname socket is returned
105 (by one of the system calls noted above),
108 offsetof(struct sockaddr_un, sun_path) + strlen(sun_path) + 1
112 contains the null-terminated pathname.
115 expression equates to the same value as
116 .IR sizeof(sa_family_t) ,
117 but some other implementations include other fields before
121 expression more portably describes the size of the address structure.)
123 For further details of pathname sockets, see below.
126 A stream socket that has not been bound to a pathname using
129 Likewise, the two sockets created by
132 When the address of an unnamed socket is returned,
134 .IR "sizeof(sa_family_t)" ,
137 should not be inspected.
138 .\" There is quite some variation across implementations: FreeBSD
139 .\" says the length is 16 bytes, HP-UX 11 says it's zero bytes.
142 an abstract socket address is distinguished (from a pathname socket)
145 is a null byte (\(aq\\0\(aq).
146 The socket's address in this namespace is given by the additional
149 that are covered by the specified length of the address structure.
150 (Null bytes in the name have no special significance.)
151 The name has no connection with filesystem pathnames.
152 When the address of an abstract socket is returned,
156 .IR "sizeof(sa_family_t)"
157 (i.e., greater than 2), and the name of the socket is contained in
159 .IR "(addrlen \- sizeof(sa_family_t))"
163 When binding a socket to a pathname, a few rules should be observed
164 for maximum portability and ease of coding:
168 should be null-terminated.
170 The length of the pathname, including the terminating null byte,
171 should not exceed the size of
176 argument that describes the enclosing
178 structure should have a value of at least:
181 offsetof(struct sockaddr_un, sun_path)+strlen(addr.sun_path)+1
187 .IR "sizeof(struct sockaddr_un)" .
189 There is some variation in how implementations handle UNIX domain
190 socket addresses that do not follow the above rules.
191 For example, some (but not all) implementations
192 .\" Linux does this, including for the case where the supplied path
194 append a null terminator if none is present in the supplied
197 When coding portable applications,
198 keep in mind that some implementations
202 as short as 92 bytes.
203 .\" Modern BSDs generally have 104, Tru64 and AIX have 104,
204 .\" Solaris and Irix have 108
211 return socket address structures.
212 When applied to UNIX domain sockets, the value-result
214 argument supplied to the call should be initialized as above.
215 Upon return, the argument is set to indicate the
217 size of the address structure.
218 The caller should check the value returned in this argument:
219 if the output value exceeds the input value,
220 then there is no guarantee that a null terminator is present in
224 .SS Pathname socket ownership and permissions
225 In the Linux implementation,
226 pathname sockets honor the permissions of the directory they are in.
227 Creation of a new socket will fail if the process does not have write and
228 search (execute) permission on the directory in which the socket is created.
231 connecting to a stream socket object requires write permission on that socket;
232 sending a datagram to a datagram socket likewise
233 requires write permission on that socket.
234 POSIX does not make any statement about the effect of the permissions
235 on a socket file, and on some systems (e.g., older BSDs),
236 the socket permissions are ignored.
237 Portable programs should not rely on
238 this feature for security.
240 When creating a new socket, the owner and group of the socket file
241 are set according to the usual rules.
242 The socket file has all permissions enabled,
243 other than those that are turned off by the process
246 The owner, group, and permissions of a pathname socket can be changed (using
250 .\" However, fchown() and fchmod() do not seem to have an effect
253 Socket permissions have no meaning for abstract sockets:
256 has no effect when binding an abstract socket,
257 and changing the ownership and permissions of the object (via
261 has no effect on the accessibility of the socket.
263 Abstract sockets automatically disappear when all open references
264 to the socket are closed.
266 The abstract socket namespace is a nonportable Linux extension.
269 For historical reasons, these socket options are specified with a
271 type even though they are
280 as the socket family.
283 Enables the receiving of the credentials of the sending process in an
285 When this option is set and the socket is not yet connected
286 a unique name in the abstract namespace will be generated automatically.
287 Expects an integer boolean flag.
294 .IR sizeof(sa_family_t) ,
295 .\" i.e., sizeof(short)
298 socket option was specified for a socket that was
299 not explicitly bound to an address,
300 then the socket is autobound to an abstract address.
301 The address consists of a null byte
302 followed by 5 bytes in the character set
304 Thus, there is a limit of 2^20 autobind addresses.
305 (From Linux 2.1.15, when the autobind feature was added,
306 8 bytes were used, and the limit was thus 2^32 autobind addresses.
307 The change to 5 bytes came in Linux 2.3.15.)
309 The following paragraphs describe domain-specific details and
310 unsupported features of the sockets API for UNIX domain sockets on Linux.
312 UNIX domain sockets do not support the transmission of
313 out-of-band data (the
323 flag is not supported by UNIX domain sockets.
331 is not supported by UNIX domain sockets.
335 socket option does have an effect for UNIX domain sockets, but the
338 For datagram sockets, the
340 value imposes an upper limit on the size of outgoing datagrams.
341 This limit is calculated as the doubled (see
343 option value less 32 bytes used for overhead.
344 .SS Ancillary messages
345 Ancillary data is sent and received using
349 For historical reasons the ancillary message types listed below
352 type even though they are
364 For more information see
368 Send or receive a set of open file descriptors from another process.
369 The data portion contains an integer array of the file descriptors.
370 The passed file descriptors behave as though they have been created with
374 Send or receive UNIX credentials.
375 This can be used for authentication.
376 The credentials are passed as a
379 Thus structure is defined in
386 pid_t pid; /* process ID of the sending process */
387 uid_t uid; /* user ID of the sending process */
388 gid_t gid; /* group ID of the sending process */
395 feature test macro must be defined (before including
397 header files) in order to obtain the definition
400 The credentials which the sender specifies are checked by the kernel.
401 A process with effective user ID 0 is allowed to specify values that do
403 The sender must specify its own process ID (unless it has the capability
405 its user ID, effective user ID, or saved set-user-ID (unless it has
407 and its group ID, effective group ID, or saved set-group-ID
414 option must be enabled on the socket.
418 calls return information in
420 The correct syntax is:
425 .IB error " = ioctl(" unix_socket ", " ioctl_type ", &" value ");"
435 socket the function returns the amount of queued unread data in the receive buffer.
436 The socket must not be in LISTEN state, otherwise an error
441 .IR <linux/sockios.h> .
442 .\" FIXME . http://sources.redhat.com/bugzilla/show_bug.cgi?id=12002,
443 .\" filed 2010-09-10, may cause SIOCINQ to be defined in glibc headers
445 you can use the synonymous
449 .\" SIOCOUTQ also has an effect for UNIX domain sockets, but not
450 .\" quite what userland might expect. It seems to return the number
451 .\" of bytes allocated for buffers containing pending output.
452 .\" That number is normally larger than the number of bytes of pending
453 .\" output. Since this info is, from userland's point of view, imprecise,
454 .\" and it may well change, probably best not to document this now.
458 the returned value is the same as
459 for Internet domain datagram socket;
465 The specified local address is already in use or the filesystem socket
466 object already exists.
469 The remote address specified by
471 was not a listening socket.
472 This error can also occur if the target pathname is not a socket.
475 Remote socket was unexpectedly closed.
478 User memory address was not valid.
481 Invalid argument passed.
482 A common cause is that the value
484 was not specified in the
486 field of passed addresses, or the socket was in an
487 invalid state for the applied operation.
491 called on an already connected socket or a target address was
492 specified on a connected socket.
495 The pathname in the remote address specified to
503 Socket operation needs a target address, but the socket is not connected.
506 Stream operation called on non-stream oriented socket or tried to
507 use the out-of-band data option.
510 The sender passed invalid credentials in the
514 Remote socket was closed on a stream socket.
518 This can be avoided by passing the
526 Passed protocol is not
530 Remote socket does not match the local socket type
538 Other errors can be generated by the generic socket layer or
539 by the filesystem while generating a filesystem socket object.
540 See the appropriate manual pages for more information.
543 and the abstract namespace were introduced with Linux 2.2 and should not
544 be used in portable programs.
545 (Some BSD-derived systems also support credential passing,
546 but the implementation details differ.)
548 Binding to a socket with a filename creates a socket
549 in the filesystem that must be deleted by the caller when it is no
552 The usual UNIX close-behind semantics apply; the socket can be unlinked
553 at any time and will be finally removed from the filesystem when the last
554 reference to it is closed.
556 To pass file descriptors or credentials over a
559 to send or receive at least one byte of nonancillary data in the same
565 UNIX domain stream sockets do not support the notion of out-of-band data.
568 When binding a socket to an address,
569 Linux is one of the implementations that appends a null terminator
570 if none is supplied in
572 In most cases this is unproblematic:
573 when the socket address is retrieved,
574 it will be one byte longer than that supplied when the socket was bound.
575 However, there is one case where confusing behavior can result:
576 if 108 non-null bytes are supplied when a socket is bound,
577 then the addition of the null terminator takes the length of
579 .IR sizeof(sun_path) .
580 Consequently, when retrieving the socket address
583 .\" The behavior on Solaris is quite similar.
586 argument for the retrieving call is specified as
587 .IR "sizeof(struct sockaddr_un)" ,
588 then the returned address structure
590 have a null terminator in
593 In addition, some implementations
594 .\" i.e., traditional BSD
595 don't require a null terminator when binding a socket (the
597 argument is used to determine the length of
599 and when the socket address is retrieved on these implementations,
600 there is no null terminator in
603 Applications that retrieve socket addresses can (portably) code
604 to handle the possibility that there is no null terminator in
606 by respecting the fact that the number of valid bytes in the pathname is:
608 strnlen(addr.sun_path, addrlen \- offsetof(sockaddr_un, sun_path))
609 .\" The following patch to amend kernel behavior was rejected:
610 .\" http://thread.gmane.org/gmane.linux.kernel.api/2437
611 .\" Subject: [patch] Fix handling of overlength pathname in AF_UNIX sun_path
613 .\" And there was a related discussion in the Austin list:
614 .\" http://thread.gmane.org/gmane.comp.standards.posix.austin.general/5735
615 .\" Subject: Having a sun_path with no null terminator
618 .\" FIXME . Track http://austingroupbugs.net/view.php?id=561
620 Alternatively, an application can retrieve
621 the socket address by allocating a buffer of size
622 .I "sizeof(struct sockaddr_un)+1"
623 that is zeroed out before the retrieval.
624 The retrieving call can specify
627 .IR "sizeof(struct sockaddr_un)" ,
628 and the extra zero byte ensures that there will be
629 a null terminator for the string returned in
636 addrlen = sizeof(struct sockaddr_un);
637 addrp = malloc(addrlen + 1);
640 memset(addrp, 0, addrlen + 1);
642 if (getsockname(sfd, (struct sockaddr *) addrp, &addrlen)) == \-1)
645 printf("sun_path = %s\\n", ((struct sockaddr_un *) addrp)\->sun_path);
649 This sort of messiness can be avoided if it is guaranteed
650 that the applications that
652 pathname sockets follow the rules outlined above under
653 .IR "Pathname sockets" .
655 The following code demonstrates the use of sequenced-packet
656 sockets for local interprocess communication.
657 It consists of two programs.
658 The server program waits for a connection from the client program.
659 The client sends each of its command-line arguments in separate messages.
660 The server treats the incoming messages as integers and adds them up.
661 The client sends the command string "END".
662 The server sends back a message containing the sum of the client's integers.
663 The client prints the sum and exits.
664 The server waits for the next client to connect.
665 To stop the server, the client is called with the command-line argument "DOWN".
667 The following output was recorded while running the server in the background
668 and repeatedly executing the client.
669 Execution of the server program ends when it receives the "DOWN" command.
677 $ \fB./client 11 \-5\fP
679 $ \fB./client DOWN\fP
691 #define SOCKET_NAME "/tmp/9Lq7BNBnBycd6nxy.socket"
692 #define BUFFER_SIZE 12
701 #include <sys/socket.h>
704 #include "connection.h"
707 main(int argc, char *argv[])
709 struct sockaddr_un name;
712 int connection_socket;
715 char buffer[BUFFER_SIZE];
718 * In case the program exited inadvertently on the last run,
724 /* Create local socket. */
726 connection_socket = socket(AF_UNIX, SOCK_SEQPACKET, 0);
727 if (connection_socket == \-1) {
733 * For portability clear the whole structure, since some
734 * implementations have additional (nonstandard) fields in
738 memset(&name, 0, sizeof(struct sockaddr_un));
740 /* Bind socket to socket name. */
742 name.sun_family = AF_UNIX;
743 strncpy(name.sun_path, SOCKET_NAME, sizeof(name.sun_path) \- 1);
745 ret = bind(connection_socket, (const struct sockaddr *) &name,
746 sizeof(struct sockaddr_un));
753 * Prepare for accepting connections. The backlog size is set
754 * to 20. So while one request is being processed other requests
758 ret = listen(connection_socket, 20);
764 /* This is the main loop for handling connections. */
768 /* Wait for incoming connection. */
770 data_socket = accept(connection_socket, NULL, NULL);
771 if (data_socket == \-1) {
779 /* Wait for next data packet. */
781 ret = read(data_socket, buffer, BUFFER_SIZE);
787 /* Ensure buffer is 0\-terminated. */
789 buffer[BUFFER_SIZE \- 1] = 0;
791 /* Handle commands. */
793 if (!strncmp(buffer, "DOWN", BUFFER_SIZE)) {
798 if (!strncmp(buffer, "END", BUFFER_SIZE)) {
802 /* Add received summand. */
804 result += atoi(buffer);
809 sprintf(buffer, "%d", result);
810 ret = write(data_socket, buffer, BUFFER_SIZE);
821 /* Quit on DOWN command. */
828 close(connection_socket);
830 /* Unlink the socket. */
845 #include <sys/socket.h>
848 #include "connection.h"
851 main(int argc, char *argv[])
853 struct sockaddr_un addr;
857 char buffer[BUFFER_SIZE];
859 /* Create local socket. */
861 data_socket = socket(AF_UNIX, SOCK_SEQPACKET, 0);
862 if (data_socket == \-1) {
868 * For portability clear the whole structure, since some
869 * implementations have additional (nonstandard) fields in
873 memset(&addr, 0, sizeof(struct sockaddr_un));
875 /* Connect socket to socket address */
877 addr.sun_family = AF_UNIX;
878 strncpy(addr.sun_path, SOCKET_NAME, sizeof(addr.sun_path) \- 1);
880 ret = connect (data_socket, (const struct sockaddr *) &addr,
881 sizeof(struct sockaddr_un));
883 fprintf(stderr, "The server is down.\\n");
887 /* Send arguments. */
889 for (i = 1; i < argc; ++i) {
890 ret = write(data_socket, argv[i], strlen(argv[i]) + 1);
897 /* Request result. */
899 strcpy (buffer, "END");
900 ret = write(data_socket, buffer, strlen(buffer) + 1);
906 /* Receive result. */
908 ret = read(data_socket, buffer, BUFFER_SIZE);
914 /* Ensure buffer is 0\-terminated. */
916 buffer[BUFFER_SIZE \- 1] = 0;
918 printf("Result = %s\\n", buffer);
928 For an example of the use of
938 .BR capabilities (7),