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  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 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 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: 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 re‐
69          turned, 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 di‐
121       rectory 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       SO_PEERSEC
199              This read-only socket option returns the security context of the
200              peer socket connected to this socket.  By default, this will  be
201              the same as the security context of the process that created the
202              peer socket unless overridden by the policy or by a process with
203              the required permissions.
204
205              The  argument  to  getsockopt(2) is a pointer to a buffer of the
206              specified length in bytes into which the security context string
207              will be copied.  If the buffer length is less than the length of
208              the security context string, then getsockopt(2) returns -1, sets
209              errno  to  ERANGE,  and  returns the required length via optlen.
210              The caller should allocate at least NAME_MAX bytes for the  buf‐
211              fer initially, although this is not guaranteed to be sufficient.
212              Resizing the buffer to the returned length and retrying  may  be
213              necessary.
214
215              The security context string may include a terminating null char‐
216              acter in the returned length, but is not guaranteed to do so:  a
217              security   context   "foo"   might   be  represented  as  either
218              {'f','o','o'} of length 3 or  {'f','o','o','\0'}  of  length  4,
219              which  are  considered  to  be  interchangeable.   The string is
220              printable, does not contain non-terminating null characters, and
221              is  in an unspecified encoding (in particular, it is not guaran‐
222              teed to be ASCII or UTF-8).
223
224              The use of this option for sockets in the AF_UNIX address family
225              is supported since Linux 2.6.2 for connected stream sockets, and
226              since Linux 4.18 also for stream and datagram socket pairs  cre‐
227              ated using socketpair(2).
228
229   Autobind feature
230       If  a  bind(2)  call  specifies  addrlen as sizeof(sa_family_t), or the
231       SO_PASSCRED socket option was specified for a socket that was  not  ex‐
232       plicitly  bound  to  an address, then the socket is autobound to an ab‐
233       stract address.  The address consists of a  null  byte  followed  by  5
234       bytes  in  the  character set [0-9a-f].  Thus, there is a limit of 2^20
235       autobind addresses.  (From Linux 2.1.15, when the autobind feature  was
236       added,  8  bytes  were  used,  and the limit was thus 2^32 autobind ad‐
237       dresses.  The change to 5 bytes came in Linux 2.3.15.)
238
239   Sockets API
240       The following paragraphs describe domain-specific  details  and  unsup‐
241       ported features of the sockets API for UNIX domain sockets on Linux.
242
243       UNIX domain sockets do not support the transmission of out-of-band data
244       (the MSG_OOB flag for send(2) and recv(2)).
245
246       The send(2) MSG_MORE flag is not supported by UNIX domain sockets.
247
248       Before Linux 3.4, the use of MSG_TRUNC in the flags argument of recv(2)
249       was not supported by UNIX domain sockets.
250
251       The  SO_SNDBUF  socket option does have an effect for UNIX domain sock‐
252       ets, but the SO_RCVBUF option does  not.   For  datagram  sockets,  the
253       SO_SNDBUF  value  imposes  an upper limit on the size of outgoing data‐
254       grams.  This limit is calculated as the doubled (see socket(7))  option
255       value less 32 bytes used for overhead.
256
257   Ancillary messages
258       Ancillary  data  is  sent and received using sendmsg(2) and recvmsg(2).
259       For historical reasons, the ancillary message types  listed  below  are
260       specified with a SOL_SOCKET type even though they are AF_UNIX specific.
261       To send them, set  the  cmsg_level  field  of  the  struct  cmsghdr  to
262       SOL_SOCKET  and the cmsg_type field to the type.  For more information,
263       see cmsg(3).
264
265       SCM_RIGHTS
266              Send or receive a set of  open  file  descriptors  from  another
267              process.  The data portion contains an integer array of the file
268              descriptors.
269
270              Commonly, this operation is referred to as "passing a  file  de‐
271              scriptor" to another process.  However, more accurately, what is
272              being passed is a reference to an  open  file  description  (see
273              open(2)),  and in the receiving process it is likely that a dif‐
274              ferent file descriptor number will be used.  Semantically,  this
275              operation  is equivalent to duplicating (dup(2)) a file descrip‐
276              tor into the file descriptor table of another process.
277
278              If the buffer used to receive the ancillary data containing file
279              descriptors is too small (or is absent), then the ancillary data
280              is truncated (or discarded) and the excess file descriptors  are
281              automatically closed in the receiving process.
282
283              If the number of file descriptors received in the ancillary data
284              would cause the process to  exceed  its  RLIMIT_NOFILE  resource
285              limit  (see getrlimit(2)), the excess file descriptors are auto‐
286              matically closed in the receiving process.
287
288              The kernel constant SCM_MAX_FD defines a limit on the number  of
289              file  descriptors  in  the  array.   Attempting to send an array
290              larger than this limit causes sendmsg(2) to fail with the  error
291              EINVAL.   SCM_MAX_FD has the value 253 (or 255 in kernels before
292              2.6.38).
293
294       SCM_CREDENTIALS
295              Send or receive UNIX credentials.  This can be used for  authen‐
296              tication.   The  credentials are passed as a struct ucred ancil‐
297              lary message.  This structure is defined  in  <sys/socket.h>  as
298              follows:
299
300                  struct ucred {
301                      pid_t pid;    /* Process ID of the sending process */
302                      uid_t uid;    /* User ID of the sending process */
303                      gid_t gid;    /* Group ID of the sending process */
304                  };
305
306              Since  glibc 2.8, the _GNU_SOURCE feature test macro must be de‐
307              fined (before including any header files) in order to obtain the
308              definition of this structure.
309
310              The  credentials  which  the sender specifies are checked by the
311              kernel.  A privileged process is allowed to specify values  that
312              do  not  match its own.  The sender must specify its own process
313              ID (unless it has the capability CAP_SYS_ADMIN,  in  which  case
314              the PID of any existing process may be specified), its real user
315              ID, effective user ID,  or  saved  set-user-ID  (unless  it  has
316              CAP_SETUID), and its real group ID, effective group ID, or saved
317              set-group-ID (unless it has CAP_SETGID).
318
319              To receive a struct ucred message, the SO_PASSCRED  option  must
320              be enabled on the socket.
321
322       SCM_SECURITY
323              Receive the SELinux security context (the security label) of the
324              peer socket.  The received ancillary data is  a  null-terminated
325              string containing the security context.  The receiver should al‐
326              locate at least NAME_MAX bytes in the data portion of the ancil‐
327              lary message for this data.
328
329              To  receive  the security context, the SO_PASSSEC option must be
330              enabled on the socket (see above).
331
332       When sending ancillary data with sendmsg(2), only one item of  each  of
333       the above types may be included in the sent message.
334
335       At  least  one  byte of real data should be sent when sending ancillary
336       data.  On Linux, this is required to successfully send  ancillary  data
337       over  a  UNIX domain stream socket.  When sending ancillary data over a
338       UNIX domain datagram socket, it is not necessary on Linux to  send  any
339       accompanying real data.  However, portable applications should also in‐
340       clude at least one byte of real data when sending ancillary data over a
341       datagram socket.
342
343       When  receiving  from  a  stream socket, ancillary data forms a kind of
344       barrier for the received data.  For example, suppose  that  the  sender
345       transmits as follows:
346
347              1. sendmsg(2) of four bytes, with no ancillary data.
348              2. sendmsg(2) of one byte, with ancillary data.
349              3. sendmsg(2) of four bytes, with no ancillary data.
350
351       Suppose  that  the  receiver  now performs recvmsg(2) calls each with a
352       buffer size of 20 bytes.  The first call will  receive  five  bytes  of
353       data, along with the ancillary data sent by the second sendmsg(2) call.
354       The next call will receive the remaining four bytes of data.
355
356       If the space allocated for receiving incoming  ancillary  data  is  too
357       small  then  the  ancillary  data is truncated to the number of headers
358       that will fit in the supplied buffer (or, in the case of an  SCM_RIGHTS
359       file  descriptor  list, the list of file descriptors may be truncated).
360       If no buffer  is  provided  for  incoming  ancillary  data  (i.e.,  the
361       msg_control  field  of  the  msghdr structure supplied to recvmsg(2) is
362       NULL), then the incoming ancillary data is discarded.  In both of these
363       cases,  the  MSG_CTRUNC flag will be set in the msg.msg_flags value re‐
364       turned by recvmsg(2).
365
366   Ioctls
367       The following ioctl(2) calls return information in value.  The  correct
368       syntax is:
369
370              int value;
371              error = ioctl(unix_socket, ioctl_type, &value);
372
373       ioctl_type can be:
374
375       SIOCINQ
376              For  SOCK_STREAM sockets, this call returns the number of unread
377              bytes in the receive buffer.  The socket must not be  in  LISTEN
378              state,  otherwise an error (EINVAL) is returned.  SIOCINQ is de‐
379              fined in <linux/sockios.h>.  Alternatively, you can use the syn‐
380              onymous  FIONREAD,  defined  in  <sys/ioctl.h>.   For SOCK_DGRAM
381              sockets, the returned value is the same as for  Internet  domain
382              datagram sockets; see udp(7).
383

ERRORS

385       EADDRINUSE
386              The  specified local address is already in use or the filesystem
387              socket object already exists.
388
389       EBADF  This error can occur for sendmsg(2) when sending a file descrip‐
390              tor  as  ancillary  data  over a UNIX domain socket (see the de‐
391              scription of SCM_RIGHTS, above), and indicates that the file de‐
392              scriptor number that is being sent is not valid (e.g., it is not
393              an open file descriptor).
394
395       ECONNREFUSED
396              The remote address specified by connect(2) was not  a  listening
397              socket.  This error can also occur if the target pathname is not
398              a socket.
399
400       ECONNRESET
401              Remote socket was unexpectedly closed.
402
403       EFAULT User memory address was not valid.
404
405       EINVAL Invalid argument passed.  A  common  cause  is  that  the  value
406              AF_UNIX  was  not  specified in the sun_type field of passed ad‐
407              dresses, or the socket was in an invalid state for  the  applied
408              operation.
409
410       EISCONN
411              connect(2) called on an already connected socket or a target ad‐
412              dress was specified on a connected socket.
413
414       ENOENT The pathname in the remote address specified to  connect(2)  did
415              not exist.
416
417       ENOMEM Out of memory.
418
419       ENOTCONN
420              Socket  operation  needs a target address, but the socket is not
421              connected.
422
423       EOPNOTSUPP
424              Stream operation called on non-stream oriented socket  or  tried
425              to use the out-of-band data option.
426
427       EPERM  The sender passed invalid credentials in the struct ucred.
428
429       EPIPE  Remote socket was closed on a stream socket.  If enabled, a SIG‐
430              PIPE is sent as well.   This  can  be  avoided  by  passing  the
431              MSG_NOSIGNAL flag to send(2) or sendmsg(2).
432
433       EPROTONOSUPPORT
434              Passed protocol is not AF_UNIX.
435
436       EPROTOTYPE
437              Remote  socket  does not match the local socket type (SOCK_DGRAM
438              versus SOCK_STREAM).
439
440       ESOCKTNOSUPPORT
441              Unknown socket type.
442
443       ESRCH  While  sending  an  ancillary  message  containing   credentials
444              (SCM_CREDENTIALS),  the  caller  specified  a  PID that does not
445              match any existing process.
446
447       ETOOMANYREFS
448              This error can occur for sendmsg(2) when sending a file descrip‐
449              tor  as  ancillary  data  over a UNIX domain socket (see the de‐
450              scription of SCM_RIGHTS, above).  It occurs  if  the  number  of
451              "in-flight"  file descriptors exceeds the RLIMIT_NOFILE resource
452              limit and the caller does not have the CAP_SYS_RESOURCE capabil‐
453              ity.  An in-flight file descriptor is one that has been sent us‐
454              ing sendmsg(2) but has not yet been accepted  in  the  recipient
455              process using recvmsg(2).
456
457              This  error  is  diagnosed since mainline Linux 4.5 (and in some
458              earlier kernel versions where the fix has been backported).   In
459              earlier  kernel  versions, it was possible to place an unlimited
460              number of file descriptors in flight, by sending each  file  de‐
461              scriptor with sendmsg(2) and then closing the file descriptor so
462              that it was not accounted  against  the  RLIMIT_NOFILE  resource
463              limit.
464
465       Other  errors  can  be  generated by the generic socket layer or by the
466       filesystem while generating a filesystem socket object.  See the appro‐
467       priate manual pages for more information.
468

VERSIONS

470       SCM_CREDENTIALS  and  the abstract namespace were introduced with Linux
471       2.2 and should not be used in  portable  programs.   (Some  BSD-derived
472       systems also support credential passing, but the implementation details
473       differ.)
474

NOTES

476       Binding to a socket with a filename creates a socket in the  filesystem
477       that  must  be deleted by the caller when it is no longer needed (using
478       unlink(2)).  The usual UNIX close-behind semantics  apply;  the  socket
479       can  be  unlinked  at  any  time  and  will be finally removed from the
480       filesystem when the last reference to it is closed.
481
482       To pass file descriptors or credentials over a SOCK_STREAM socket,  you
483       must  to  send or receive at least one byte of nonancillary data in the
484       same sendmsg(2) or recvmsg(2) call.
485
486       UNIX domain stream sockets do not support  the  notion  of  out-of-band
487       data.
488

BUGS

490       When  binding  a  socket to an address, Linux is one of the implementa‐
491       tions that appends a null terminator if none is supplied  in  sun_path.
492       In  most  cases  this  is unproblematic: when the socket address is re‐
493       trieved, it will be one byte longer than that supplied when the  socket
494       was bound.  However, there is one case where confusing behavior can re‐
495       sult: if 108 non-null bytes are supplied when a socket is  bound,  then
496       the  addition  of  the null terminator takes the length of the pathname
497       beyond sizeof(sun_path).  Consequently, when retrieving the socket  ad‐
498       dress  (for  example, via accept(2)), if the input addrlen argument for
499       the retrieving call is specified as  sizeof(struct  sockaddr_un),  then
500       the  returned  address  structure  won't  have  a  null  terminator  in
501       sun_path.
502
503       In addition, some implementations don't require a null terminator  when
504       binding  a socket (the addrlen argument is used to determine the length
505       of sun_path) and when the socket address is retrieved on  these  imple‐
506       mentations, there is no null terminator in sun_path.
507
508       Applications that retrieve socket addresses can (portably) code to han‐
509       dle the possibility that there is no null terminator in sun_path by re‐
510       specting the fact that the number of valid bytes in the pathname is:
511
512           strnlen(addr.sun_path, addrlen - offsetof(sockaddr_un, sun_path))
513
514       Alternatively,  an application can retrieve the socket address by allo‐
515       cating a buffer of size sizeof(struct sockaddr_un)+1 that is zeroed out
516       before  the  retrieval.   The  retrieving  call  can specify addrlen as
517       sizeof(struct sockaddr_un), and the extra zero byte ensures that  there
518       will be a null terminator for the string returned in sun_path:
519
520           void *addrp;
521
522           addrlen = sizeof(struct sockaddr_un);
523           addrp = malloc(addrlen + 1);
524           if (addrp == NULL)
525               /* Handle error */ ;
526           memset(addrp, 0, addrlen + 1);
527
528           if (getsockname(sfd, (struct sockaddr *) addrp, &addrlen)) == -1)
529               /* handle error */ ;
530
531           printf("sun_path = %s\n", ((struct sockaddr_un *) addrp)->sun_path);
532
533       This  sort of messiness can be avoided if it is guaranteed that the ap‐
534       plications that create pathname sockets follow the rules outlined above
535       under Pathname sockets.
536

EXAMPLES

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

SEE ALSO

802       recvmsg(2),  sendmsg(2),  socket(2),  socketpair(2), cmsg(3), capabili‐
803       ties(7), credentials(7), socket(7), udp(7)
804

COLOPHON

806       This page is part of release 5.12 of the Linux  man-pages  project.   A
807       description  of  the project, information about reporting bugs, and the
808       latest    version    of    this    page,    can     be     found     at
809       https://www.kernel.org/doc/man-pages/.
810
811
812
813Linux                             2021-03-22                           UNIX(7)
Impressum