# phpman > man > unix(7)

[UNIX(7)](https://www.chedong.com/phpMan.php/man/UNIX/7/markdown)                               Linux Programmer's Manual                              [UNIX(7)](https://www.chedong.com/phpMan.php/man/UNIX/7/markdown)



## NAME
       unix - sockets for local interprocess communication

## SYNOPSIS
### #include <sys/socket.h>
### #include <sys/un.h>

       _unix_socket_ **=** **socket(AF**___**UNIX,** **type,** **0);**
       _error_ **=** **socketpair(AF**___**UNIX,** **type,** **0,** **int** *****_sv_**);**

## DESCRIPTION
       The  **AF**___**UNIX**  (also known as **AF**___**LOCAL**) socket family is used to communicate between processes
       on the same machine efficiently.  Traditionally, UNIX domain sockets can be  either  unnamed,
       or  bound  to a filesystem pathname (marked as being of type socket).  Linux also supports an
       abstract namespace which is independent of the filesystem.

       Valid socket types in the  UNIX  domain  are:  **SOCK**___**STREAM**,  for  a  stream-oriented  socket;
       **SOCK**___**DGRAM**, for a datagram-oriented socket that preserves message boundaries (as on most UNIX
       implementations, UNIX domain datagram sockets are always reliable  and  don't  reorder  data‐
       grams); and (since Linux 2.6.4) **SOCK**___**SEQPACKET**, for a sequenced-packet socket that is connec‐
       tion-oriented, preserves message boundaries, and delivers messages in  the  order  that  they
       were sent.

       UNIX  domain  sockets  support  passing file descriptors or process credentials to other pro‐
       cesses using ancillary data.

### Address format
       A UNIX domain socket address is represented in the following structure:

           struct sockaddr_un {
               sa_family_t sun_family;               /* AF_UNIX */
               char        sun_path[108];            /* Pathname */
           };

       The _sun_family_ field always contains **AF**___**UNIX**.  On Linux, _sun_path_ is 108 bytes in  size;  see
       also NOTES, below.

       Various  systems  calls  (for example, [**bind**(2)](https://www.chedong.com/phpMan.php/man/bind/2/markdown), [**connect**(2)](https://www.chedong.com/phpMan.php/man/connect/2/markdown), and [**sendto**(2)](https://www.chedong.com/phpMan.php/man/sendto/2/markdown)) take a _sockaddr_un_
       argument as input.  Some other system calls  (for  example,  [**getsockname**(2)](https://www.chedong.com/phpMan.php/man/getsockname/2/markdown),  [**getpeername**(2)](https://www.chedong.com/phpMan.php/man/getpeername/2/markdown),
       [**recvfrom**(2)](https://www.chedong.com/phpMan.php/man/recvfrom/2/markdown), and [**accept**(2)](https://www.chedong.com/phpMan.php/man/accept/2/markdown)) return an argument of this type.

       Three types of address are distinguished in the _sockaddr_un_ structure:

       *  _pathname_: a UNIX domain socket can be bound to a null-terminated filesystem pathname using
          [**bind**(2)](https://www.chedong.com/phpMan.php/man/bind/2/markdown).  When the address of a pathname socket is returned (by one of  the  system  calls
          noted above), its length is

              offsetof(struct sockaddr_un, sun_path) + strlen(sun_path) + 1

          and  _sun_path_  contains the null-terminated pathname.  (On Linux, the above **offsetof**() ex‐
          pression equates to the same value as _sizeof(sa_family_t)_, but some other  implementations
          include other fields before _sun_path_, so the **offsetof**() expression more portably describes
          the size of the address structure.)

          For further details of pathname sockets, see below.

       *  _unnamed_: A stream socket that has not been bound to a pathname using [**bind**(2)](https://www.chedong.com/phpMan.php/man/bind/2/markdown) has no  name.
          Likewise,  the  two  sockets created by [**socketpair**(2)](https://www.chedong.com/phpMan.php/man/socketpair/2/markdown) are unnamed.  When the address of an
          unnamed socket is returned, its length is _sizeof(sa_family_t)_, and _sun_path_ should not  be
          inspected.

       *  _abstract_: an abstract socket address is distinguished (from a pathname socket) by the fact
          that _sun_path[0]_ is a null byte ('\0').  The socket's address in this namespace  is  given
          by  the  additional  bytes in _sun_path_ that are covered by the specified length of the ad‐
          dress structure.  (Null bytes in the name have no special significance.)  The name has  no
          connection with filesystem pathnames.  When the address of an abstract socket is returned,
          the returned _addrlen_ is greater than _sizeof(sa_family_t)_ (i.e., greater than 2),  and  the
          name  of  the  socket  is  contained in the first _(addrlen_ _-_ _sizeof(sa_family_t))_ bytes of
          _sun_path_.

### Pathname sockets
       When binding a socket to a pathname, a few rules should be observed for  maximum  portability
       and ease of coding:

       *  The pathname in _sun_path_ should be null-terminated.

       *  The  length  of  the  pathname, including the terminating null byte, should not exceed the
          size of _sun_path_.

       *  The _addrlen_ argument that describes the enclosing  _sockaddr_un_  structure  should  have  a
          value of at least:

              offsetof(struct sockaddr_un, sun_path)+strlen(addr.sun_path)+1

          or, more simply, _addrlen_ can be specified as _sizeof(struct_ _sockaddr_un)_.

       There  is  some  variation in how implementations handle UNIX domain socket addresses that do
       not follow the above rules.  For example, some (but not all) implementations  append  a  null
       terminator if none is present in the supplied _sun_path_.

       When  coding  portable  applications, keep in mind that some implementations have _sun_path_ as
       short as 92 bytes.

       Various system calls ([**accept**(2)](https://www.chedong.com/phpMan.php/man/accept/2/markdown), [**recvfrom**(2)](https://www.chedong.com/phpMan.php/man/recvfrom/2/markdown), [**getsockname**(2)](https://www.chedong.com/phpMan.php/man/getsockname/2/markdown), [**getpeername**(2)](https://www.chedong.com/phpMan.php/man/getpeername/2/markdown))  return  socket
       address  structures.   When applied to UNIX domain sockets, the value-result _addrlen_ argument
       supplied to the call should be initialized as above.  Upon return, the argument is set to in‐
       dicate  the _actual_ size of the address structure.  The caller should check the value returned
       in this argument: if the output value exceeds the input value, then  there  is  no  guarantee
       that a null terminator is present in _sun_path_.  (See BUGS.)

### Pathname socket ownership and permissions
       In the Linux implementation, pathname sockets honor the permissions of the directory they are
       in.  Creation of a new socket fails if the process does not have write and  search  (execute)
       permission on the directory in which the socket is created.

       On  Linux,  connecting  to  a  stream socket object requires write permission on that socket;
       sending a datagram to a datagram socket likewise requires write permission  on  that  socket.
       POSIX  does  not make any statement about the effect of the permissions on a socket file, and
       on some systems (e.g., older BSDs), the socket permissions are  ignored.   Portable  programs
       should not rely on this feature for security.

       When  creating  a new socket, the owner and group of the socket file are set according to the
       usual rules.  The socket file has all permissions enabled, other than those that  are  turned
       off by the process [**umask**(2)](https://www.chedong.com/phpMan.php/man/umask/2/markdown).

       The  owner,  group,  and  permissions of a pathname socket can be changed (using [**chown**(2)](https://www.chedong.com/phpMan.php/man/chown/2/markdown) and
       [**chmod**(2)](https://www.chedong.com/phpMan.php/man/chmod/2/markdown)).

### Abstract sockets
       Socket permissions have no meaning for abstract sockets: the process [**umask**(2)](https://www.chedong.com/phpMan.php/man/umask/2/markdown) has  no  effect
       when  binding  an  abstract  socket, and changing the ownership and permissions of the object
       (via [**fchown**(2)](https://www.chedong.com/phpMan.php/man/fchown/2/markdown) and [**fchmod**(2)](https://www.chedong.com/phpMan.php/man/fchmod/2/markdown)) has no effect on the accessibility of the socket.

       Abstract sockets automatically disappear when all open references to the socket are closed.

       The abstract socket namespace is a nonportable Linux extension.

### Socket options
       For historical reasons, these socket options are specified with a **SOL**___**SOCKET** type even though
       they are **AF**___**UNIX** specific.  They can be set with [**setsockopt**(2)](https://www.chedong.com/phpMan.php/man/setsockopt/2/markdown) and read with [**getsockopt**(2)](https://www.chedong.com/phpMan.php/man/getsockopt/2/markdown) by
       specifying **SOL**___**SOCKET** as the socket family.

       **SO**___**PASSCRED**
              Enabling this socket option causes receipt of the credentials of the  sending  process
              in  an  **SCM**___**CREDENTIALS**  **ancillary** message in each subsequently received message.  The
              returned credentials are those specified by the sender using **SCM**___**CREDENTIALS**, or a de‐
              fault  that  includes the sender's PID, real user ID, and real group ID, if the sender
              did not specify **SCM**___**CREDENTIALS** ancillary data.

              When this option is set and the socket is not yet connected, a unique name in the  ab‐
              stract namespace will be generated automatically.

              The value given as an argument to [**setsockopt**(2)](https://www.chedong.com/phpMan.php/man/setsockopt/2/markdown) and returned as the result of **getsock**‐‐
              [**opt**(2)](https://www.chedong.com/phpMan.php/man/opt/2/markdown) is an integer boolean flag.

       **SO**___**PASSSEC**
              Enables receiving of the SELinux security label of the peer  socket  in  an  ancillary
              message of type **SCM**___**SECURITY** (see below).

              The value given as an argument to [**setsockopt**(2)](https://www.chedong.com/phpMan.php/man/setsockopt/2/markdown) and returned as the result of **getsock**‐‐
              [**opt**(2)](https://www.chedong.com/phpMan.php/man/opt/2/markdown) is an integer boolean flag.

              The **SO**___**PASSSEC** option is supported  for  UNIX  domain  datagram  sockets  since  Linux
              2.6.18; support for UNIX domain stream sockets was added in Linux 4.2.

       **SO**___**PEEK**___**OFF**
              See [**socket**(7)](https://www.chedong.com/phpMan.php/man/socket/7/markdown).

       **SO**___**PEERCRED**
              This  read-only socket option returns the credentials of the peer process connected to
              this socket.  The returned credentials are those that were in effect at  the  time  of
              the call to [**connect**(2)](https://www.chedong.com/phpMan.php/man/connect/2/markdown) or [**socketpair**(2)](https://www.chedong.com/phpMan.php/man/socketpair/2/markdown).

              The  argument  to  [**getsockopt**(2)](https://www.chedong.com/phpMan.php/man/getsockopt/2/markdown)  is  a  pointer  to  a  _ucred_  structure;  define the
              ___**GNU**___**SOURCE** feature test macro  to  obtain  the  definition  of  that  structure  from
              _<sys/socket.h>_.

              The  use  of this option is possible only for connected **AF**___**UNIX** stream sockets and for
              **AF**___**UNIX** stream and datagram socket pairs created using [**socketpair**(2)](https://www.chedong.com/phpMan.php/man/socketpair/2/markdown).

       **SO**___**PEERSEC**
              This read-only socket option returns the security context of the peer socket connected
              to  this  socket.   By  default,  this will be the same as the security context of the
              process that created the peer socket unless overridden by the policy or by  a  process
              with the required permissions.

              The  argument  to  [**getsockopt**(2)](https://www.chedong.com/phpMan.php/man/getsockopt/2/markdown)  is  a pointer to a buffer of the specified length in
              bytes into which the security context string will be copied.  If the buffer length  is
              less  than  the  length of the security context string, then [**getsockopt**(2)](https://www.chedong.com/phpMan.php/man/getsockopt/2/markdown) returns -1,
              sets _errno_ to **ERANGE**, and returns the required length via _optlen_.  The  caller  should
              allocate  at least **NAME**___**MAX** bytes for the buffer initially, although this is not guar‐
              anteed to be sufficient.  Resizing the buffer to the returned length and retrying  may
              be necessary.

              The  security  context string may include a terminating null character in the returned
              length, but is not guaranteed to do so: a security context "foo" might be  represented
              as  either {'f','o','o'} of length 3 or {'f','o','o','\0'} of length 4, which are con‐
              sidered to be interchangeable.  The string is printable, does not  contain  non-termi‐
              nating  null  characters,  and is in an unspecified encoding (in particular, it is not
              guaranteed to be ASCII or UTF-8).

              The use of this option for sockets in the **AF**___**UNIX** address family  is  supported  since
              Linux  2.6.2  for  connected  stream sockets, and since Linux 4.18 also for stream and
              datagram socket pairs created using [**socketpair**(2)](https://www.chedong.com/phpMan.php/man/socketpair/2/markdown).

### Autobind feature
       If a [**bind**(2)](https://www.chedong.com/phpMan.php/man/bind/2/markdown) call specifies _addrlen_ as _sizeof(sa_family_t)_, or the **SO**___**PASSCRED** socket  option
       was  specified  for  a socket that was not explicitly bound to an address, then the socket is
       autobound to an abstract address.  The address consists of a null byte followed by 5 bytes in
       the  character set _[0-9a-f]_.  Thus, there is a limit of 2^20 autobind addresses.  (From Linux
       2.1.15, when the autobind feature was added, 8 bytes were used, and the limit was  thus  2^32
       autobind addresses.  The change to 5 bytes came in Linux 2.3.15.)

### Sockets API
       The  following  paragraphs  describe  domain-specific details and unsupported features of the
       sockets API for UNIX domain sockets on Linux.

       UNIX domain sockets do not support the transmission of out-of-band data (the **MSG**___**OOB** flag for
       [**send**(2)](https://www.chedong.com/phpMan.php/man/send/2/markdown) and [**recv**(2)](https://www.chedong.com/phpMan.php/man/recv/2/markdown)).

       The [**send**(2)](https://www.chedong.com/phpMan.php/man/send/2/markdown) **MSG**___**MORE** flag is not supported by UNIX domain sockets.

       Before  Linux 3.4, the use of **MSG**___**TRUNC** in the _flags_ argument of [**recv**(2)](https://www.chedong.com/phpMan.php/man/recv/2/markdown) was not supported by
       UNIX domain sockets.

       The **SO**___**SNDBUF** socket option does have an effect for UNIX domain sockets,  but  the  **SO**___**RCVBUF**
       option  does  not.   For  datagram sockets, the **SO**___**SNDBUF** value imposes an upper limit on the
       size of outgoing datagrams.  This limit is calculated as the doubled (see  [**socket**(7)](https://www.chedong.com/phpMan.php/man/socket/7/markdown))  option
       value less 32 bytes used for overhead.

### Ancillary messages
       Ancillary data is sent and received using [**sendmsg**(2)](https://www.chedong.com/phpMan.php/man/sendmsg/2/markdown) and [**recvmsg**(2)](https://www.chedong.com/phpMan.php/man/recvmsg/2/markdown).  For historical reasons,
       the ancillary message types listed below are specified with a  **SOL**___**SOCKET**  type  even  though
       they  are  **AF**___**UNIX** specific.  To send them, set the _cmsg_level_ field of the struct _cmsghdr_ to
       **SOL**___**SOCKET** and the _cmsg_type_ field to the type.  For more information, see [**cmsg**(3)](https://www.chedong.com/phpMan.php/man/cmsg/3/markdown).

       **SCM**___**RIGHTS**
              Send or receive a set of open file descriptors from another process.  The data portion
              contains an integer array of the file descriptors.

              Commonly,  this  operation  is  referred  to as "passing a file descriptor" to another
              process.  However, more accurately, what is being passed is a  reference  to  an  open
              file  description (see [**open**(2)](https://www.chedong.com/phpMan.php/man/open/2/markdown)), and in the receiving process it is likely that a dif‐
              ferent file descriptor number will be used.  Semantically, this operation  is  equiva‐
              lent  to  duplicating ([**dup**(2)](https://www.chedong.com/phpMan.php/man/dup/2/markdown)) a file descriptor into the file descriptor table of an‐
              other process.

              If the buffer used to receive the ancillary data containing file  descriptors  is  too
              small  (or is absent), then the ancillary data is truncated (or discarded) and the ex‐
              cess file descriptors are automatically closed in the receiving process.

              If the number of file descriptors received in  the  ancillary  data  would  cause  the
              process to exceed its **RLIMIT**___**NOFILE** resource limit (see [**getrlimit**(2)](https://www.chedong.com/phpMan.php/man/getrlimit/2/markdown)), the excess file
              descriptors are automatically closed in the receiving process.

              The kernel constant **SCM**___**MAX**___**FD** defines a limit on the number of  file  descriptors  in
              the  array.   Attempting  to send an array larger than this limit causes [**sendmsg**(2)](https://www.chedong.com/phpMan.php/man/sendmsg/2/markdown) to
              fail with the error **EINVAL**.  **SCM**___**MAX**___**FD** has the value 253 (or 255  in  kernels  before
              2.6.38).

       **SCM**___**CREDENTIALS**
              Send  or  receive UNIX credentials.  This can be used for authentication.  The creden‐
              tials are passed as a _struct_ _ucred_ ancillary message.  This structure  is  defined  in
              _<sys/socket.h>_ as follows:

                  struct ucred {
                      pid_t pid;    /* Process ID of the sending process */
                      uid_t uid;    /* User ID of the sending process */
                      gid_t gid;    /* Group ID of the sending process */
                  };

              Since  glibc 2.8, the ___**GNU**___**SOURCE** feature test macro must be defined (before including
              _any_ header files) in order to obtain the definition of this structure.

              The credentials which the sender specifies are checked by the  kernel.   A  privileged
              process is allowed to specify values that do not match its own.  The sender must spec‐
              ify its own process ID (unless it has the capability **CAP**___**SYS**___**ADMIN**, in which case  the
              PID of any existing process may be specified), its real user ID, effective user ID, or
              saved set-user-ID (unless it has **CAP**___**SETUID**), and its real group ID,  effective  group
              ID, or saved set-group-ID (unless it has **CAP**___**SETGID**).

              To  receive  a  _struct_  _ucred_  message,  the **SO**___**PASSCRED** option must be enabled on the
              socket.

       **SCM**___**SECURITY**
              Receive the SELinux security context (the security label) of the peer socket.  The re‐
              ceived  ancillary  data  is  a null-terminated string containing the security context.
              The receiver should allocate at least **NAME**___**MAX** bytes in the data portion of the ancil‐
              lary message for this data.

              To  receive  the security context, the **SO**___**PASSSEC** option must be enabled on the socket
              (see above).

       When sending ancillary data with [**sendmsg**(2)](https://www.chedong.com/phpMan.php/man/sendmsg/2/markdown), only one item of each of the above types may  be
       included in the sent message.

       At least one byte of real data should be sent when sending ancillary data.  On Linux, this is
       required to successfully send ancillary data over a UNIX domain stream socket.  When  sending
       ancillary  data  over a UNIX domain datagram socket, it is not necessary on Linux to send any
       accompanying real data.  However, portable applications should also include at least one byte
       of real data when sending ancillary data over a datagram socket.

       When  receiving from a stream socket, ancillary data forms a kind of barrier for the received
       data.  For example, suppose that the sender transmits as follows:

              1. [**sendmsg**(2)](https://www.chedong.com/phpMan.php/man/sendmsg/2/markdown) of four bytes, with no ancillary data.
              2. [**sendmsg**(2)](https://www.chedong.com/phpMan.php/man/sendmsg/2/markdown) of one byte, with ancillary data.
              3. [**sendmsg**(2)](https://www.chedong.com/phpMan.php/man/sendmsg/2/markdown) of four bytes, with no ancillary data.

       Suppose that the receiver now performs [**recvmsg**(2)](https://www.chedong.com/phpMan.php/man/recvmsg/2/markdown) calls each with a buffer size of 20  bytes.
       The  first  call  will  receive five bytes of data, along with the ancillary data sent by the
       second [**sendmsg**(2)](https://www.chedong.com/phpMan.php/man/sendmsg/2/markdown) call.  The next call will receive the remaining four bytes of data.

       If the space allocated for receiving incoming ancillary data is too small then the  ancillary
       data  is  truncated to the number of headers that will fit in the supplied buffer (or, in the
       case of an **SCM**___**RIGHTS** file descriptor list, the list of file descriptors may  be  truncated).
       If  no buffer is provided for incoming ancillary data (i.e., the _msg_control_ field of the _ms__‐
       _ghdr_ structure supplied to [**recvmsg**(2)](https://www.chedong.com/phpMan.php/man/recvmsg/2/markdown) is NULL), then the  incoming  ancillary  data  is  dis‐
       carded.   In  both of these cases, the **MSG**___**CTRUNC** flag will be set in the _msg.msg_flags_ value
       returned by [**recvmsg**(2)](https://www.chedong.com/phpMan.php/man/recvmsg/2/markdown).

### Ioctls
       The following [**ioctl**(2)](https://www.chedong.com/phpMan.php/man/ioctl/2/markdown) calls return information in _value_.  The correct syntax is:

              **int** _value_**;**
              _error_ **=** **ioctl(**_unix_socket_**,** _ioctl_type_**,** **&**_value_**);**

       _ioctl_type_ can be:

       **SIOCINQ**
              For **SOCK**___**STREAM** sockets, this call returns the number of unread bytes in  the  receive
              buffer.   The  socket  must not be in LISTEN state, otherwise an error (**EINVAL**) is re‐
              turned.  **SIOCINQ** is defined in _<linux/sockios.h>_.  Alternatively, you can use the syn‐
              onymous  **FIONREAD**,  defined  in  _<sys/ioctl.h>_.   For **SOCK**___**DGRAM** sockets, the returned
              value is the same as for Internet domain datagram sockets; see [**udp**(7)](https://www.chedong.com/phpMan.php/man/udp/7/markdown).

## ERRORS
       **EADDRINUSE**
              The specified local address is already in use or the filesystem socket object  already
              exists.

       **EBADF**  This  error  can occur for [**sendmsg**(2)](https://www.chedong.com/phpMan.php/man/sendmsg/2/markdown) when sending a file descriptor as ancillary data
              over a UNIX domain socket (see the description of **SCM**___**RIGHTS**,  above),  and  indicates
              that  the  file  descriptor number that is being sent is not valid (e.g., it is not an
              open file descriptor).

       **ECONNREFUSED**
              The remote address specified by [**connect**(2)](https://www.chedong.com/phpMan.php/man/connect/2/markdown) was not a listening socket.  This error can
              also occur if the target pathname is not a socket.

       **ECONNRESET**
              Remote socket was unexpectedly closed.

       **EFAULT** User memory address was not valid.

       **EINVAL** Invalid  argument  passed.  A common cause is that the value **AF**___**UNIX** was not specified
              in the _sun_type_ field of passed addresses, or the socket was in an invalid  state  for
              the applied operation.

       **EISCONN**
              [**connect**(2)](https://www.chedong.com/phpMan.php/man/connect/2/markdown)  called on an already connected socket or a target address was specified on
              a connected socket.

       **ENOENT** The pathname in the remote address specified to [**connect**(2)](https://www.chedong.com/phpMan.php/man/connect/2/markdown) did not exist.

       **ENOMEM** Out of memory.

       **ENOTCONN**
              Socket operation needs a target address, but the socket is not connected.

       **EOPNOTSUPP**
              Stream operation called on non-stream oriented socket or tried to use the  out-of-band
              data option.

       **EPERM**  The sender passed invalid credentials in the _struct_ _ucred_.

       **EPIPE**  Remote  socket  was closed on a stream socket.  If enabled, a **SIGPIPE** is sent as well.
              This can be avoided by passing the **MSG**___**NOSIGNAL** flag to [**send**(2)](https://www.chedong.com/phpMan.php/man/send/2/markdown) or [**sendmsg**(2)](https://www.chedong.com/phpMan.php/man/sendmsg/2/markdown).

       **EPROTONOSUPPORT**
              Passed protocol is not **AF**___**UNIX**.

       **EPROTOTYPE**
              Remote socket does not match the local socket type (**SOCK**___**DGRAM** versus **SOCK**___**STREAM**).

       **ESOCKTNOSUPPORT**
              Unknown socket type.

       **ESRCH**  While sending an  ancillary  message  containing  credentials  (**SCM**___**CREDENTIALS**),  the
              caller specified a PID that does not match any existing process.

       **ETOOMANYREFS**
              This  error  can occur for [**sendmsg**(2)](https://www.chedong.com/phpMan.php/man/sendmsg/2/markdown) when sending a file descriptor as ancillary data
              over a UNIX domain socket (see the description of **SCM**___**RIGHTS**, above).   It  occurs  if
              the  number  of  "in-flight" file descriptors exceeds the **RLIMIT**___**NOFILE** resource limit
              and the caller does not have the **CAP**___**SYS**___**RESOURCE** capability.  An in-flight  file  de‐
              scriptor  is  one that has been sent using [**sendmsg**(2)](https://www.chedong.com/phpMan.php/man/sendmsg/2/markdown) but has not yet been accepted in
              the recipient process using [**recvmsg**(2)](https://www.chedong.com/phpMan.php/man/recvmsg/2/markdown).

              This error is diagnosed since mainline Linux 4.5 (and in some earlier kernel  versions
              where  the  fix  has been backported).  In earlier kernel versions, it was possible to
              place an unlimited number of file descriptors in flight, by sending each file descrip‐
              tor  with [**sendmsg**(2)](https://www.chedong.com/phpMan.php/man/sendmsg/2/markdown) and then closing the file descriptor so that it was not accounted
              against the **RLIMIT**___**NOFILE** resource limit.

       Other errors can be generated by the generic socket layer or by the filesystem while generat‐
       ing a filesystem socket object.  See the appropriate manual pages for more information.

## VERSIONS
       **SCM**___**CREDENTIALS**  and  the abstract namespace were introduced with Linux 2.2 and should not be
       used in portable programs.  (Some BSD-derived systems also support  credential  passing,  but
       the implementation details differ.)

## NOTES
       Binding  to  a socket with a filename creates a socket in the filesystem that must be deleted
       by the caller when it is no longer needed (using [**unlink**(2)](https://www.chedong.com/phpMan.php/man/unlink/2/markdown)).  The usual UNIX close-behind se‐
       mantics  apply;  the  socket can be unlinked at any time and will be finally removed from the
       filesystem when the last reference to it is closed.

       To pass file descriptors or credentials over a **SOCK**___**STREAM** socket, you must to  send  or  re‐
       ceive at least one byte of nonancillary data in the same [**sendmsg**(2)](https://www.chedong.com/phpMan.php/man/sendmsg/2/markdown) or [**recvmsg**(2)](https://www.chedong.com/phpMan.php/man/recvmsg/2/markdown) call.

       UNIX domain stream sockets do not support the notion of out-of-band data.

## BUGS
       When  binding a socket to an address, Linux is one of the implementations that appends a null
       terminator if none is supplied in _sun_path_.  In most cases this is  unproblematic:  when  the
       socket  address  is  retrieved, it will be one byte longer than that supplied when the socket
       was bound.  However, there is one case where confusing behavior can result: if  108  non-null
       bytes are supplied when a socket is bound, then the addition of the null terminator takes the
       length of the pathname beyond _sizeof(sun_path)_.  Consequently, when retrieving the socket ad‐
       dress  (for example, via [**accept**(2)](https://www.chedong.com/phpMan.php/man/accept/2/markdown)), if the input _addrlen_ argument for the retrieving call is
       specified as _sizeof(struct_ _sockaddr_un)_, then the returned address  structure  _won't_  have  a
       null terminator in _sun_path_.

       In  addition, some implementations don't require a null terminator when binding a socket (the
       _addrlen_ argument is used to determine the length of _sun_path_) and when the socket address  is
       retrieved on these implementations, there is no null terminator in _sun_path_.

       Applications  that  retrieve  socket  addresses can (portably) code to handle the possibility
       that there is no null terminator in _sun_path_ by respecting the fact that the number of  valid
       bytes in the pathname is:

           strnlen(addr.sun_path, addrlen - offsetof(sockaddr_un, sun_path))

       Alternatively,  an application can retrieve the socket address by allocating a buffer of size
       _sizeof(struct_ _sockaddr_un)+1_ that is zeroed out before the retrieval.   The  retrieving  call
       can specify _addrlen_ as _sizeof(struct_ _sockaddr_un)_, and the extra zero byte ensures that there
       will be a null terminator for the string returned in _sun_path_:

           void *addrp;

           addrlen = sizeof(struct sockaddr_un);
           addrp = malloc(addrlen + 1);
           if (addrp == NULL)
               /* Handle error */ ;
           memset(addrp, 0, addrlen + 1);

           if (getsockname(sfd, (struct sockaddr *) addrp, &addrlen)) == -1)
               /* handle error */ ;

           printf("sun_path = %s\n", ((struct sockaddr_un *) addrp)->sun_path);

       This sort of messiness can be avoided if it is guaranteed that the applications  that  _create_
       pathname sockets follow the rules outlined above under _Pathname_ _sockets_.

## EXAMPLES
       The  following  code  demonstrates the use of sequenced-packet sockets for local interprocess
       communication.  It consists of two programs.  The server program waits for a connection  from
       the  client  program.   The  client sends each of its command-line arguments in separate mes‐
       sages.  The server treats the incoming messages as integers and adds  them  up.   The  client
       sends  the  command  string "END".  The server sends back a message containing the sum of the
       client's integers.  The client prints the sum and exits.   The  server  waits  for  the  next
       client  to  connect.  To stop the server, the client is called with the command-line argument
       "DOWN".

       The following output was recorded while running the server in the background  and  repeatedly
       executing  the client.  Execution of the server program ends when it receives the "DOWN" com‐
       mand.

### Example output
           $ **./server** **&**
           [1] 25887
           $ **./client** **3** **4**
           Result = 7
           $ **./client** **11** **-5**
           Result = 6
           $ **./client** **DOWN**
           Result = 0
           [1]+  Done                    ./server
           $

### Program source

       /*
        * File connection.h
        */

       #define SOCKET_NAME "/tmp/9Lq7BNBnBycd6nxy.socket"
       #define BUFFER_SIZE 12

       /*
        * File server.c
        */

       #include <stdio.h>
       #include <stdlib.h>
       #include <string.h>
       #include <sys/socket.h>
       #include <sys/un.h>
       #include <unistd.h>
       #include "connection.h"

       int
       main(int argc, char *argv[])
       {
           struct sockaddr_un name;
           int down_flag = 0;
           int ret;
           int connection_socket;
           int data_socket;
           int result;
           char buffer[BUFFER_SIZE];

           /* Create local socket. */

           connection_socket = socket(AF_UNIX, SOCK_SEQPACKET, 0);
           if (connection_socket == -1) {
               perror("socket");
               exit(EXIT_FAILURE);
           }

           /*
            * For portability clear the whole structure, since some
            * implementations have additional (nonstandard) fields in
            * the structure.
            */

           memset(&name, 0, [sizeof(name)](https://www.chedong.com/phpMan.php/man/sizeof/name/markdown));

           /* Bind socket to socket name. */

           name.sun_family = AF_UNIX;
           strncpy(name.sun_path, SOCKET_NAME, sizeof(name.sun_path) - 1);

           ret = bind(connection_socket, (const struct sockaddr *) &name,
                      [sizeof(name)](https://www.chedong.com/phpMan.php/man/sizeof/name/markdown));
           if (ret == -1) {
               perror("bind");
               exit(EXIT_FAILURE);
           }

           /*
            * Prepare for accepting connections. The backlog size is set
            * to 20. So while one request is being processed other requests
            * can be waiting.
            */

           ret = listen(connection_socket, 20);
           if (ret == -1) {
               perror("listen");
               exit(EXIT_FAILURE);
           }

           /* This is the main loop for handling connections. */

           for (;;) {

               /* Wait for incoming connection. */

               data_socket = accept(connection_socket, NULL, NULL);
               if (data_socket == -1) {
                   perror("accept");
                   exit(EXIT_FAILURE);
               }

               result = 0;
               for (;;) {

                   /* Wait for next data packet. */

                   ret = read(data_socket, buffer, sizeof(buffer));
                   if (ret == -1) {
                       perror("read");
                       exit(EXIT_FAILURE);
                   }

                   /* Ensure buffer is 0-terminated. */

                   buffer[sizeof(buffer) - 1] = 0;

                   /* Handle commands. */

                   if (!strncmp(buffer, "DOWN", sizeof(buffer))) {
                       down_flag = 1;
                       break;
                   }

                   if (!strncmp(buffer, "END", sizeof(buffer))) {
                       break;
                   }

                   /* Add received summand. */

                   result += atoi(buffer);
               }

               /* Send result. */

               sprintf(buffer, "%d", result);
               ret = write(data_socket, buffer, sizeof(buffer));
               if (ret == -1) {
                   perror("write");
                   exit(EXIT_FAILURE);
               }

               /* Close socket. */

               close(data_socket);

               /* Quit on DOWN command. */

               if (down_flag) {
                   break;
               }
           }

           close(connection_socket);

           /* Unlink the socket. */

           unlink(SOCKET_NAME);

           exit(EXIT_SUCCESS);
       }

       /*
        * File client.c
        */

       #include <errno.h>
       #include <stdio.h>
       #include <stdlib.h>
       #include <string.h>
       #include <sys/socket.h>
       #include <sys/un.h>
       #include <unistd.h>
       #include "connection.h"

       int
       main(int argc, char *argv[])
       {
           struct sockaddr_un addr;
           int ret;
           int data_socket;
           char buffer[BUFFER_SIZE];

           /* Create local socket. */

           data_socket = socket(AF_UNIX, SOCK_SEQPACKET, 0);
           if (data_socket == -1) {
               perror("socket");
               exit(EXIT_FAILURE);
           }

           /*
            * For portability clear the whole structure, since some
            * implementations have additional (nonstandard) fields in
            * the structure.
            */

           memset(&addr, 0, sizeof(addr));

           /* Connect socket to socket address */

           addr.sun_family = AF_UNIX;
           strncpy(addr.sun_path, SOCKET_NAME, sizeof(addr.sun_path) - 1);

           ret = connect(data_socket, (const struct sockaddr *) &addr,
                          sizeof(addr));
           if (ret == -1) {
               fprintf(stderr, "The server is down.\n");
               exit(EXIT_FAILURE);
           }

           /* Send arguments. */

           for (int i = 1; i < argc; ++i) {
               ret = write(data_socket, argv[i], strlen(argv[i]) + 1);
               if (ret == -1) {
                   perror("write");
                   break;
               }
           }

           /* Request result. */

           strcpy(buffer, "END");
           ret = write(data_socket, buffer, strlen(buffer) + 1);
           if (ret == -1) {
               perror("write");
               exit(EXIT_FAILURE);
           }

           /* Receive result. */

           ret = read(data_socket, buffer, sizeof(buffer));
           if (ret == -1) {
               perror("read");
               exit(EXIT_FAILURE);
           }

           /* Ensure buffer is 0-terminated. */

           buffer[sizeof(buffer) - 1] = 0;

           printf("Result = %s\n", buffer);

           /* Close socket. */

           close(data_socket);

           exit(EXIT_SUCCESS);
       }

       For an example of the use of **SCM**___**RIGHTS** see [**cmsg**(3)](https://www.chedong.com/phpMan.php/man/cmsg/3/markdown).

## SEE ALSO
       [**recvmsg**(2)](https://www.chedong.com/phpMan.php/man/recvmsg/2/markdown), [**sendmsg**(2)](https://www.chedong.com/phpMan.php/man/sendmsg/2/markdown), [**socket**(2)](https://www.chedong.com/phpMan.php/man/socket/2/markdown), [**socketpair**(2)](https://www.chedong.com/phpMan.php/man/socketpair/2/markdown), [**cmsg**(3)](https://www.chedong.com/phpMan.php/man/cmsg/3/markdown),  [**capabilities**(7)](https://www.chedong.com/phpMan.php/man/capabilities/7/markdown),  [**credentials**(7)](https://www.chedong.com/phpMan.php/man/credentials/7/markdown),
       [**socket**(7)](https://www.chedong.com/phpMan.php/man/socket/7/markdown), [**udp**(7)](https://www.chedong.com/phpMan.php/man/udp/7/markdown)

## COLOPHON
       This  page  is  part  of  release  5.10 of the Linux _man-pages_ project.  A description of the
       project, information about reporting bugs, and the latest version of this page, can be  found
       at <https://www.kernel.org/doc/man-pages/>.



Linux                                        2020-11-01                                      [UNIX(7)](https://www.chedong.com/phpMan.php/man/UNIX/7/markdown)
