1UNIX(7)                    Linux Programmer's Manual                   UNIX(7)
2
3
4

NAME

6       unix - sockets for local interprocess communication
7

SYNOPSIS

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

DESCRIPTION

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.  This 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,  in  which  case
283              the PID of any existing process may be specified), its real user
284              ID, effective user ID,  or  saved  set-user-ID  (unless  it  has
285              CAP_SETUID), and its real group ID, effective group ID, or saved
286              set-group-ID (unless it has CAP_SETGID).
287
288              To receive a struct ucred message, the SO_PASSCRED  option  must
289              be enabled on the socket.
290
291       SCM_SECURITY
292              Receive the SELinux security context (the security label) of the
293              peer socket.  The received ancillary data is  a  null-terminated
294              string  containing  the  security  context.  The receiver should
295              allocate at least NAME_MAX bytes in  the  data  portion  of  the
296              ancillary message for this data.
297
298              To  receive  the security context, the SO_PASSSEC option must be
299              enabled on the socket (see above).
300
301       When sending ancillary data with sendmsg(2), only one item of  each  of
302       the above types may be included in the sent message.
303
304       At  least  one  byte of real data should be sent when sending ancillary
305       data.  On Linux, this is required to successfully send  ancillary  data
306       over  a  UNIX domain stream socket.  When sending ancillary data over a
307       UNIX domain datagram socket, it is not necessary on Linux to  send  any
308       accompanying  real  data.   However,  portable applications should also
309       include at least one byte of real data when sending ancillary data over
310       a datagram socket.
311
312       When  receiving  from  a  stream socket, ancillary data forms a kind of
313       barrier for the received data.  For example, suppose  that  the  sender
314       transmits as follows:
315
316              1. sendmsg(2) of four bytes, with no ancillary data.
317              2. sendmsg(2) of one byte, with ancillary data.
318              3. sendmsg(2) of four bytes, with no ancillary data.
319
320       Suppose  that  the  receiver  now performs recvmsg(2) calls each with a
321       buffer size of 20 bytes.  The first call will  receive  five  bytes  of
322       data, along with the ancillary data sent by the second sendmsg(2) call.
323       The next call will receive the remaining four bytes of data.
324
325       If the space allocated for receiving incoming  ancillary  data  is  too
326       small  then  the  ancillary  data is truncated to the number of headers
327       that will fit in the supplied buffer (or, in the case of an  SCM_RIGHTS
328       file  descriptor  list, the list of file descriptors may be truncated).
329       If no buffer  is  provided  for  incoming  ancillary  data  (i.e.,  the
330       msg_control  field  of  the  msghdr structure supplied to recvmsg(2) is
331       NULL), then the incoming ancillary data is discarded.  In both of these
332       cases,  the  MSG_CTRUNC  flag  will  be  set in the msg.msg_flags value
333       returned by recvmsg(2).
334
335   Ioctls
336       The following ioctl(2) calls return information in value.  The  correct
337       syntax is:
338
339              int value;
340              error = ioctl(unix_socket, ioctl_type, &value);
341
342       ioctl_type can be:
343
344       SIOCINQ
345              For  SOCK_STREAM sockets, this call returns the number of unread
346              bytes in the receive buffer.  The socket must not be  in  LISTEN
347              state,  otherwise  an  error  (EINVAL)  is returned.  SIOCINQ is
348              defined in <linux/sockios.h>.  Alternatively, you  can  use  the
349              synonymous  FIONREAD,  defined in <sys/ioctl.h>.  For SOCK_DGRAM
350              sockets, the returned value is the same as for  Internet  domain
351              datagram sockets; see udp(7).
352

ERRORS

354       EADDRINUSE
355              The  specified local address is already in use or the filesystem
356              socket object already exists.
357
358       EBADF  This error can occur for sendmsg(2) when sending a file descrip‐
359              tor  as  ancillary  data  over  a  UNIX  domain  socket (see the
360              description of SCM_RIGHTS, above), and indicates that  the  file
361              descriptor  number  that is being sent is not valid (e.g., it is
362              not an open file descriptor).
363
364       ECONNREFUSED
365              The remote address specified by connect(2) was not  a  listening
366              socket.  This error can also occur if the target pathname is not
367              a socket.
368
369       ECONNRESET
370              Remote socket was unexpectedly closed.
371
372       EFAULT User memory address was not valid.
373
374       EINVAL Invalid argument passed.  A  common  cause  is  that  the  value
375              AF_UNIX  was  not  specified  in  the  sun_type  field of passed
376              addresses, or the socket was in an invalid state for the applied
377              operation.
378
379       EISCONN
380              connect(2)  called  on  an  already connected socket or a target
381              address was specified on a connected socket.
382
383       ENOENT The pathname in the remote address specified to  connect(2)  did
384              not exist.
385
386       ENOMEM Out of memory.
387
388       ENOTCONN
389              Socket  operation  needs a target address, but the socket is not
390              connected.
391
392       EOPNOTSUPP
393              Stream operation called on non-stream oriented socket  or  tried
394              to use the out-of-band data option.
395
396       EPERM  The sender passed invalid credentials in the struct ucred.
397
398       EPIPE  Remote socket was closed on a stream socket.  If enabled, a SIG‐
399              PIPE is sent as well.   This  can  be  avoided  by  passing  the
400              MSG_NOSIGNAL flag to send(2) or sendmsg(2).
401
402       EPROTONOSUPPORT
403              Passed protocol is not AF_UNIX.
404
405       EPROTOTYPE
406              Remote  socket  does not match the local socket type (SOCK_DGRAM
407              versus SOCK_STREAM).
408
409       ESOCKTNOSUPPORT
410              Unknown socket type.
411
412       ESRCH  While  sending  an  ancillary  message  containing   credentials
413              (SCM_CREDENTIALS),  the  caller  specified  a  PID that does not
414              match any existing process.
415
416       ETOOMANYREFS
417              This error can occur for sendmsg(2) when sending a file descrip‐
418              tor  as  ancillary  data  over  a  UNIX  domain  socket (see the
419              description of SCM_RIGHTS, above).  It occurs if the  number  of
420              "in-flight"  file descriptors exceeds the RLIMIT_NOFILE resource
421              limit and the caller does not have the CAP_SYS_RESOURCE capabil‐
422              ity.   An  in-flight  file  descriptor is one that has been sent
423              using sendmsg(2) but has not yet been accepted in the  recipient
424              process using recvmsg(2).
425
426              This  error  is  diagnosed since mainline Linux 4.5 (and in some
427              earlier kernel versions where the fix has been backported).   In
428              earlier  kernel  versions, it was possible to place an unlimited
429              number of file descriptors  in  flight,  by  sending  each  file
430              descriptor  with sendmsg(2) and then closing the file descriptor
431              so that it was not accounted against the RLIMIT_NOFILE  resource
432              limit.
433
434       Other  errors  can  be  generated by the generic socket layer or by the
435       filesystem while generating a filesystem socket object.  See the appro‐
436       priate manual pages for more information.
437

VERSIONS

439       SCM_CREDENTIALS  and  the abstract namespace were introduced with Linux
440       2.2 and should not be used in  portable  programs.   (Some  BSD-derived
441       systems also support credential passing, but the implementation details
442       differ.)
443

NOTES

445       Binding to a socket with a filename creates a socket in the  filesystem
446       that  must  be deleted by the caller when it is no longer needed (using
447       unlink(2)).  The usual UNIX close-behind semantics  apply;  the  socket
448       can  be  unlinked  at  any  time  and  will be finally removed from the
449       filesystem when the last reference to it is closed.
450
451       To pass file descriptors or credentials over a SOCK_STREAM socket,  you
452       must  to  send or receive at least one byte of nonancillary data in the
453       same sendmsg(2) or recvmsg(2) call.
454
455       UNIX domain stream sockets do not support  the  notion  of  out-of-band
456       data.
457

BUGS

459       When  binding  a  socket to an address, Linux is one of the implementa‐
460       tions that appends a null terminator if none is supplied  in  sun_path.
461       In  most  cases  this  is  unproblematic:  when  the  socket address is
462       retrieved, it will be one byte  longer  than  that  supplied  when  the
463       socket  was bound.  However, there is one case where confusing behavior
464       can result: if 108 non-null bytes are supplied when a socket is  bound,
465       then  the addition of the null terminator takes the length of the path‐
466       name beyond sizeof(sun_path).  Consequently, when retrieving the socket
467       address (for example, via accept(2)), if the input addrlen argument for
468       the retrieving call is specified as  sizeof(struct  sockaddr_un),  then
469       the  returned  address  structure  won't  have  a  null  terminator  in
470       sun_path.
471
472       In addition, some implementations don't require a null terminator  when
473       binding  a socket (the addrlen argument is used to determine the length
474       of sun_path) and when the socket address is retrieved on  these  imple‐
475       mentations, there is no null terminator in sun_path.
476
477       Applications that retrieve socket addresses can (portably) code to han‐
478       dle the possibility that there is no null  terminator  in  sun_path  by
479       respecting the fact that the number of valid bytes in the pathname is:
480
481           strnlen(addr.sun_path, addrlen - offsetof(sockaddr_un, sun_path))
482
483       Alternatively,  an application can retrieve the socket address by allo‐
484       cating a buffer of size sizeof(struct sockaddr_un)+1 that is zeroed out
485       before  the  retrieval.   The  retrieving  call  can specify addrlen as
486       sizeof(struct sockaddr_un), and the extra zero byte ensures that  there
487       will be a null terminator for the string returned in sun_path:
488
489           void *addrp;
490
491           addrlen = sizeof(struct sockaddr_un);
492           addrp = malloc(addrlen + 1);
493           if (addrp == NULL)
494               /* Handle error */ ;
495           memset(addrp, 0, addrlen + 1);
496
497           if (getsockname(sfd, (struct sockaddr *) addrp, &addrlen)) == -1)
498               /* handle error */ ;
499
500           printf("sun_path = %s\n", ((struct sockaddr_un *) addrp)->sun_path);
501
502       This  sort  of  messiness  can  be avoided if it is guaranteed that the
503       applications that create pathname sockets  follow  the  rules  outlined
504       above under Pathname sockets.
505

EXAMPLES

507       The following code demonstrates the use of sequenced-packet sockets for
508       local interprocess communication.  It consists of  two  programs.   The
509       server  program  waits  for  a connection from the client program.  The
510       client sends each of its command-line arguments in  separate  messages.
511       The  server  treats the incoming messages as integers and adds them up.
512       The client sends the command string "END".  The  server  sends  back  a
513       message containing the sum of the client's integers.  The client prints
514       the sum and exits.  The server waits for the next  client  to  connect.
515       To stop the server, the client is called with the command-line argument
516       "DOWN".
517
518       The following output was recorded while running the server in the back‐
519       ground  and  repeatedly  executing the client.  Execution of the server
520       program ends when it receives the "DOWN" command.
521
522   Example output
523           $ ./server &
524           [1] 25887
525           $ ./client 3 4
526           Result = 7
527           $ ./client 11 -5
528           Result = 6
529           $ ./client DOWN
530           Result = 0
531           [1]+  Done                    ./server
532           $
533
534   Program source
535
536       /*
537        * File connection.h
538        */
539
540       #define SOCKET_NAME "/tmp/9Lq7BNBnBycd6nxy.socket"
541       #define BUFFER_SIZE 12
542
543       /*
544        * File server.c
545        */
546
547       #include <stdio.h>
548       #include <stdlib.h>
549       #include <string.h>
550       #include <sys/socket.h>
551       #include <sys/un.h>
552       #include <unistd.h>
553       #include "connection.h"
554
555       int
556       main(int argc, char *argv[])
557       {
558           struct sockaddr_un name;
559           int down_flag = 0;
560           int ret;
561           int connection_socket;
562           int data_socket;
563           int result;
564           char buffer[BUFFER_SIZE];
565
566           /* Create local socket. */
567
568           connection_socket = socket(AF_UNIX, SOCK_SEQPACKET, 0);
569           if (connection_socket == -1) {
570               perror("socket");
571               exit(EXIT_FAILURE);
572           }
573
574           /*
575            * For portability clear the whole structure, since some
576            * implementations have additional (nonstandard) fields in
577            * the structure.
578            */
579
580           memset(&name, 0, sizeof(struct sockaddr_un));
581
582           /* Bind socket to socket name. */
583
584           name.sun_family = AF_UNIX;
585           strncpy(name.sun_path, SOCKET_NAME, sizeof(name.sun_path) - 1);
586
587           ret = bind(connection_socket, (const struct sockaddr *) &name,
588                      sizeof(struct sockaddr_un));
589           if (ret == -1) {
590               perror("bind");
591               exit(EXIT_FAILURE);
592           }
593
594           /*
595            * Prepare for accepting connections. The backlog size is set
596            * to 20. So while one request is being processed other requests
597            * can be waiting.
598            */
599
600           ret = listen(connection_socket, 20);
601           if (ret == -1) {
602               perror("listen");
603               exit(EXIT_FAILURE);
604           }
605
606           /* This is the main loop for handling connections. */
607
608           for (;;) {
609
610               /* Wait for incoming connection. */
611
612               data_socket = accept(connection_socket, NULL, NULL);
613               if (data_socket == -1) {
614                   perror("accept");
615                   exit(EXIT_FAILURE);
616               }
617
618               result = 0;
619               for (;;) {
620
621                   /* Wait for next data packet. */
622
623                   ret = read(data_socket, buffer, BUFFER_SIZE);
624                   if (ret == -1) {
625                       perror("read");
626                       exit(EXIT_FAILURE);
627                   }
628
629                   /* Ensure buffer is 0-terminated. */
630
631                   buffer[BUFFER_SIZE - 1] = 0;
632
633                   /* Handle commands. */
634
635                   if (!strncmp(buffer, "DOWN", BUFFER_SIZE)) {
636                       down_flag = 1;
637                       break;
638                   }
639
640                   if (!strncmp(buffer, "END", BUFFER_SIZE)) {
641                       break;
642                   }
643
644                   /* Add received summand. */
645
646                   result += atoi(buffer);
647               }
648
649               /* Send result. */
650
651               sprintf(buffer, "%d", result);
652               ret = write(data_socket, buffer, BUFFER_SIZE);
653               if (ret == -1) {
654                   perror("write");
655                   exit(EXIT_FAILURE);
656               }
657
658               /* Close socket. */
659
660               close(data_socket);
661
662               /* Quit on DOWN command. */
663
664               if (down_flag) {
665                   break;
666               }
667           }
668
669           close(connection_socket);
670
671           /* Unlink the socket. */
672
673           unlink(SOCKET_NAME);
674
675           exit(EXIT_SUCCESS);
676       }
677
678       /*
679        * File client.c
680        */
681
682       #include <errno.h>
683       #include <stdio.h>
684       #include <stdlib.h>
685       #include <string.h>
686       #include <sys/socket.h>
687       #include <sys/un.h>
688       #include <unistd.h>
689       #include "connection.h"
690
691       int
692       main(int argc, char *argv[])
693       {
694           struct sockaddr_un addr;
695           int i;
696           int ret;
697           int data_socket;
698           char buffer[BUFFER_SIZE];
699
700           /* Create local socket. */
701
702           data_socket = socket(AF_UNIX, SOCK_SEQPACKET, 0);
703           if (data_socket == -1) {
704               perror("socket");
705               exit(EXIT_FAILURE);
706           }
707
708           /*
709            * For portability clear the whole structure, since some
710            * implementations have additional (nonstandard) fields in
711            * the structure.
712            */
713
714           memset(&addr, 0, sizeof(struct sockaddr_un));
715
716           /* Connect socket to socket address */
717
718           addr.sun_family = AF_UNIX;
719           strncpy(addr.sun_path, SOCKET_NAME, sizeof(addr.sun_path) - 1);
720
721           ret = connect (data_socket, (const struct sockaddr *) &addr,
722                          sizeof(struct sockaddr_un));
723           if (ret == -1) {
724               fprintf(stderr, "The server is down.\n");
725               exit(EXIT_FAILURE);
726           }
727
728           /* Send arguments. */
729
730           for (i = 1; i < argc; ++i) {
731               ret = write(data_socket, argv[i], strlen(argv[i]) + 1);
732               if (ret == -1) {
733                   perror("write");
734                   break;
735               }
736           }
737
738           /* Request result. */
739
740           strcpy (buffer, "END");
741           ret = write(data_socket, buffer, strlen(buffer) + 1);
742           if (ret == -1) {
743               perror("write");
744               exit(EXIT_FAILURE);
745           }
746
747           /* Receive result. */
748
749           ret = read(data_socket, buffer, BUFFER_SIZE);
750           if (ret == -1) {
751               perror("read");
752               exit(EXIT_FAILURE);
753           }
754
755           /* Ensure buffer is 0-terminated. */
756
757           buffer[BUFFER_SIZE - 1] = 0;
758
759           printf("Result = %s\n", buffer);
760
761           /* Close socket. */
762
763           close(data_socket);
764
765           exit(EXIT_SUCCESS);
766       }
767
768       For an example of the use of SCM_RIGHTS see cmsg(3).
769

SEE ALSO

771       recvmsg(2), sendmsg(2), socket(2),  socketpair(2),  cmsg(3),  capabili‐
772       ties(7), credentials(7), socket(7), udp(7)
773

COLOPHON

775       This  page  is  part of release 5.07 of the Linux man-pages project.  A
776       description of the project, information about reporting bugs,  and  the
777       latest     version     of     this    page,    can    be    found    at
778       https://www.kernel.org/doc/man-pages/.
779
780
781
782Linux                             2020-06-09                           UNIX(7)
Impressum