{
    "content": [
        {
            "type": "text",
            "text": "# unix (man)\n\n## NAME\n\nunix - sockets for local interprocess communication\n\n## DESCRIPTION\n\nThe  AFUNIX  (also known as AFLOCAL) socket family is used to communicate between processes\non the same machine efficiently.  Traditionally, UNIX domain sockets can be  either  unnamed,\nor  bound  to a filesystem pathname (marked as being of type socket).  Linux also supports an\nabstract namespace which is independent of the filesystem.\n\n## Sections\n\n- **NAME**\n- **SYNOPSIS** (2 subsections)\n- **DESCRIPTION** (9 subsections)\n- **ERRORS**\n- **VERSIONS**\n- **NOTES**\n- **BUGS**\n- **EXAMPLES** (2 subsections)\n- **SEE ALSO**\n- **COLOPHON**\n\nUse structuredContent.sections for detailed options, examples, and full documentation.\n"
        }
    ],
    "structuredContent": {
        "command": "unix",
        "section": "",
        "mode": "man",
        "summary": "unix - sockets for local interprocess communication",
        "synopsis": "",
        "tldr_summary": null,
        "tldr_examples": [],
        "tldr_source": null,
        "flags": [],
        "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.",
            "$ ./server &",
            "[1] 25887",
            "$ ./client 3 4",
            "Result = 7",
            "$ ./client 11 -5",
            "Result = 6",
            "$ ./client DOWN",
            "Result = 0",
            "[1]+  Done                    ./server",
            "/*",
            "* File connection.h",
            "*/",
            "#define SOCKETNAME \"/tmp/9Lq7BNBnBycd6nxy.socket\"",
            "#define BUFFERSIZE 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 sockaddrun name;",
            "int downflag = 0;",
            "int ret;",
            "int connectionsocket;",
            "int datasocket;",
            "int result;",
            "char buffer[BUFFERSIZE];",
            "/* Create local socket. */",
            "connectionsocket = socket(AFUNIX, SOCKSEQPACKET, 0);",
            "if (connectionsocket == -1) {",
            "perror(\"socket\");",
            "exit(EXITFAILURE);",
            "/*",
            "* For portability clear the whole structure, since some",
            "* implementations have additional (nonstandard) fields in",
            "* the structure.",
            "*/",
            "memset(&name, 0, sizeof(name));",
            "/* Bind socket to socket name. */",
            "name.sunfamily = AFUNIX;",
            "strncpy(name.sunpath, SOCKETNAME, sizeof(name.sunpath) - 1);",
            "ret = bind(connectionsocket, (const struct sockaddr *) &name,",
            "sizeof(name));",
            "if (ret == -1) {",
            "perror(\"bind\");",
            "exit(EXITFAILURE);",
            "/*",
            "* 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(connectionsocket, 20);",
            "if (ret == -1) {",
            "perror(\"listen\");",
            "exit(EXITFAILURE);",
            "/* This is the main loop for handling connections. */",
            "for (;;) {",
            "/* Wait for incoming connection. */",
            "datasocket = accept(connectionsocket, NULL, NULL);",
            "if (datasocket == -1) {",
            "perror(\"accept\");",
            "exit(EXITFAILURE);",
            "result = 0;",
            "for (;;) {",
            "/* Wait for next data packet. */",
            "ret = read(datasocket, buffer, sizeof(buffer));",
            "if (ret == -1) {",
            "perror(\"read\");",
            "exit(EXITFAILURE);",
            "/* Ensure buffer is 0-terminated. */",
            "buffer[sizeof(buffer) - 1] = 0;",
            "/* Handle commands. */",
            "if (!strncmp(buffer, \"DOWN\", sizeof(buffer))) {",
            "downflag = 1;",
            "break;",
            "if (!strncmp(buffer, \"END\", sizeof(buffer))) {",
            "break;",
            "/* Add received summand. */",
            "result += atoi(buffer);",
            "/* Send result. */",
            "sprintf(buffer, \"%d\", result);",
            "ret = write(datasocket, buffer, sizeof(buffer));",
            "if (ret == -1) {",
            "perror(\"write\");",
            "exit(EXITFAILURE);",
            "/* Close socket. */",
            "close(datasocket);",
            "/* Quit on DOWN command. */",
            "if (downflag) {",
            "break;",
            "close(connectionsocket);",
            "/* Unlink the socket. */",
            "unlink(SOCKETNAME);",
            "exit(EXITSUCCESS);",
            "/*",
            "* 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 sockaddrun addr;",
            "int ret;",
            "int datasocket;",
            "char buffer[BUFFERSIZE];",
            "/* Create local socket. */",
            "datasocket = socket(AFUNIX, SOCKSEQPACKET, 0);",
            "if (datasocket == -1) {",
            "perror(\"socket\");",
            "exit(EXITFAILURE);",
            "/*",
            "* 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.sunfamily = AFUNIX;",
            "strncpy(addr.sunpath, SOCKETNAME, sizeof(addr.sunpath) - 1);",
            "ret = connect(datasocket, (const struct sockaddr *) &addr,",
            "sizeof(addr));",
            "if (ret == -1) {",
            "fprintf(stderr, \"The server is down.\\n\");",
            "exit(EXITFAILURE);",
            "/* Send arguments. */",
            "for (int i = 1; i < argc; ++i) {",
            "ret = write(datasocket, argv[i], strlen(argv[i]) + 1);",
            "if (ret == -1) {",
            "perror(\"write\");",
            "break;",
            "/* Request result. */",
            "strcpy(buffer, \"END\");",
            "ret = write(datasocket, buffer, strlen(buffer) + 1);",
            "if (ret == -1) {",
            "perror(\"write\");",
            "exit(EXITFAILURE);",
            "/* Receive result. */",
            "ret = read(datasocket, buffer, sizeof(buffer));",
            "if (ret == -1) {",
            "perror(\"read\");",
            "exit(EXITFAILURE);",
            "/* Ensure buffer is 0-terminated. */",
            "buffer[sizeof(buffer) - 1] = 0;",
            "printf(\"Result = %s\\n\", buffer);",
            "/* Close socket. */",
            "close(datasocket);",
            "exit(EXITSUCCESS);",
            "For an example of the use of SCMRIGHTS see cmsg(3)."
        ],
        "see_also": [
            {
                "name": "recvmsg",
                "section": "2",
                "url": "https://www.chedong.com/phpMan.php/man/recvmsg/2/json"
            },
            {
                "name": "sendmsg",
                "section": "2",
                "url": "https://www.chedong.com/phpMan.php/man/sendmsg/2/json"
            },
            {
                "name": "socket",
                "section": "2",
                "url": "https://www.chedong.com/phpMan.php/man/socket/2/json"
            },
            {
                "name": "socketpair",
                "section": "2",
                "url": "https://www.chedong.com/phpMan.php/man/socketpair/2/json"
            },
            {
                "name": "cmsg",
                "section": "3",
                "url": "https://www.chedong.com/phpMan.php/man/cmsg/3/json"
            },
            {
                "name": "capabilities",
                "section": "7",
                "url": "https://www.chedong.com/phpMan.php/man/capabilities/7/json"
            },
            {
                "name": "credentials",
                "section": "7",
                "url": "https://www.chedong.com/phpMan.php/man/credentials/7/json"
            },
            {
                "name": "socket",
                "section": "7",
                "url": "https://www.chedong.com/phpMan.php/man/socket/7/json"
            },
            {
                "name": "udp",
                "section": "7",
                "url": "https://www.chedong.com/phpMan.php/man/udp/7/json"
            }
        ],
        "section_outline": [
            {
                "name": "NAME",
                "lines": 2,
                "subsections": []
            },
            {
                "name": "SYNOPSIS",
                "lines": 1,
                "subsections": [
                    {
                        "name": "#include <sys/socket.h>",
                        "lines": 1
                    },
                    {
                        "name": "#include <sys/un.h>",
                        "lines": 3
                    }
                ]
            },
            {
                "name": "DESCRIPTION",
                "lines": 15,
                "subsections": [
                    {
                        "name": "Address format",
                        "lines": 43
                    },
                    {
                        "name": "Pathname sockets",
                        "lines": 29
                    },
                    {
                        "name": "Pathname socket ownership and permissions",
                        "lines": 17
                    },
                    {
                        "name": "Abstract sockets",
                        "lines": 8
                    },
                    {
                        "name": "Socket options",
                        "lines": 67
                    },
                    {
                        "name": "Autobind feature",
                        "lines": 7
                    },
                    {
                        "name": "Sockets API",
                        "lines": 16
                    },
                    {
                        "name": "Ancillary messages",
                        "lines": 90
                    },
                    {
                        "name": "Ioctls",
                        "lines": 14
                    }
                ]
            },
            {
                "name": "ERRORS",
                "lines": 71,
                "subsections": []
            },
            {
                "name": "VERSIONS",
                "lines": 4,
                "subsections": []
            },
            {
                "name": "NOTES",
                "lines": 10,
                "subsections": []
            },
            {
                "name": "BUGS",
                "lines": 41,
                "subsections": []
            },
            {
                "name": "EXAMPLES",
                "lines": 13,
                "subsections": [
                    {
                        "name": "Example output",
                        "lines": 11
                    },
                    {
                        "name": "Program source",
                        "lines": 233
                    }
                ]
            },
            {
                "name": "SEE ALSO",
                "lines": 3,
                "subsections": []
            },
            {
                "name": "COLOPHON",
                "lines": 7,
                "subsections": []
            }
        ],
        "sections": {
            "NAME": {
                "content": "unix - sockets for local interprocess communication\n",
                "subsections": []
            },
            "SYNOPSIS": {
                "content": "",
                "subsections": [
                    {
                        "name": "#include <sys/socket.h>",
                        "content": ""
                    },
                    {
                        "name": "#include <sys/un.h>",
                        "content": "unixsocket = socket(AFUNIX, type, 0);\nerror = socketpair(AFUNIX, type, 0, int *sv);\n"
                    }
                ]
            },
            "DESCRIPTION": {
                "content": "The  AFUNIX  (also known as AFLOCAL) socket family is used to communicate between processes\non the same machine efficiently.  Traditionally, UNIX domain sockets can be  either  unnamed,\nor  bound  to a filesystem pathname (marked as being of type socket).  Linux also supports an\nabstract namespace which is independent of the filesystem.\n\nValid socket types in the  UNIX  domain  are:  SOCKSTREAM,  for  a  stream-oriented  socket;\nSOCKDGRAM, for a datagram-oriented socket that preserves message boundaries (as on most UNIX\nimplementations, UNIX domain datagram sockets are always reliable  and  don't  reorder  data‐\ngrams); and (since Linux 2.6.4) SOCKSEQPACKET, for a sequenced-packet socket that is connec‐\ntion-oriented, preserves message boundaries, and delivers messages in  the  order  that  they\nwere sent.\n\nUNIX  domain  sockets  support  passing file descriptors or process credentials to other pro‐\ncesses using ancillary data.\n",
                "subsections": [
                    {
                        "name": "Address format",
                        "content": "A UNIX domain socket address is represented in the following structure:\n\nstruct sockaddrun {\nsafamilyt sunfamily;               /* AFUNIX */\nchar        sunpath[108];            /* Pathname */\n};\n\nThe sunfamily field always contains AFUNIX.  On Linux, sunpath is 108 bytes in  size;  see\nalso NOTES, below.\n\nVarious  systems  calls  (for example, bind(2), connect(2), and sendto(2)) take a sockaddrun\nargument as input.  Some other system calls  (for  example,  getsockname(2),  getpeername(2),\nrecvfrom(2), and accept(2)) return an argument of this type.\n\nThree types of address are distinguished in the sockaddrun structure:\n\n*  pathname: a UNIX domain socket can be bound to a null-terminated filesystem pathname using\nbind(2).  When the address of a pathname socket is returned (by one of  the  system  calls\nnoted above), its length is\n\noffsetof(struct sockaddrun, sunpath) + strlen(sunpath) + 1\n\nand  sunpath  contains the null-terminated pathname.  (On Linux, the above offsetof() ex‐\npression equates to the same value as sizeof(safamilyt), but some other  implementations\ninclude other fields before sunpath, so the offsetof() expression more portably describes\nthe size of the address structure.)\n\nFor further details of pathname sockets, see below.\n\n*  unnamed: A stream socket that has not been bound to a pathname using bind(2) has no  name.\nLikewise,  the  two  sockets created by socketpair(2) are unnamed.  When the address of an\nunnamed socket is returned, its length is sizeof(safamilyt), and sunpath should not  be\ninspected.\n\n*  abstract: an abstract socket address is distinguished (from a pathname socket) by the fact\nthat sunpath[0] is a null byte ('\\0').  The socket's address in this namespace  is  given\nby  the  additional  bytes in sunpath that are covered by the specified length of the ad‐\ndress structure.  (Null bytes in the name have no special significance.)  The name has  no\nconnection with filesystem pathnames.  When the address of an abstract socket is returned,\nthe returned addrlen is greater than sizeof(safamilyt) (i.e., greater than 2),  and  the\nname  of  the  socket  is  contained in the first (addrlen - sizeof(safamilyt)) bytes of\nsunpath.\n"
                    },
                    {
                        "name": "Pathname sockets",
                        "content": "When binding a socket to a pathname, a few rules should be observed for  maximum  portability\nand ease of coding:\n\n*  The pathname in sunpath should be null-terminated.\n\n*  The  length  of  the  pathname, including the terminating null byte, should not exceed the\nsize of sunpath.\n\n*  The addrlen argument that describes the enclosing  sockaddrun  structure  should  have  a\nvalue of at least:\n\noffsetof(struct sockaddrun, sunpath)+strlen(addr.sunpath)+1\n\nor, more simply, addrlen can be specified as sizeof(struct sockaddrun).\n\nThere  is  some  variation in how implementations handle UNIX domain socket addresses that do\nnot follow the above rules.  For example, some (but not all) implementations  append  a  null\nterminator if none is present in the supplied sunpath.\n\nWhen  coding  portable  applications, keep in mind that some implementations have sunpath as\nshort as 92 bytes.\n\nVarious system calls (accept(2), recvfrom(2), getsockname(2), getpeername(2))  return  socket\naddress  structures.   When applied to UNIX domain sockets, the value-result addrlen argument\nsupplied to the call should be initialized as above.  Upon return, the argument is set to in‐\ndicate  the actual size of the address structure.  The caller should check the value returned\nin this argument: if the output value exceeds the input value, then  there  is  no  guarantee\nthat a null terminator is present in sunpath.  (See BUGS.)\n"
                    },
                    {
                        "name": "Pathname socket ownership and permissions",
                        "content": "In the Linux implementation, pathname sockets honor the permissions of the directory they are\nin.  Creation of a new socket fails if the process does not have write and  search  (execute)\npermission on the directory in which the socket is created.\n\nOn  Linux,  connecting  to  a  stream socket object requires write permission on that socket;\nsending a datagram to a datagram socket likewise requires write permission  on  that  socket.\nPOSIX  does  not make any statement about the effect of the permissions on a socket file, and\non some systems (e.g., older BSDs), the socket permissions are  ignored.   Portable  programs\nshould not rely on this feature for security.\n\nWhen  creating  a new socket, the owner and group of the socket file are set according to the\nusual rules.  The socket file has all permissions enabled, other than those that  are  turned\noff by the process umask(2).\n\nThe  owner,  group,  and  permissions of a pathname socket can be changed (using chown(2) and\nchmod(2)).\n"
                    },
                    {
                        "name": "Abstract sockets",
                        "content": "Socket permissions have no meaning for abstract sockets: the process umask(2) has  no  effect\nwhen  binding  an  abstract  socket, and changing the ownership and permissions of the object\n(via fchown(2) and fchmod(2)) has no effect on the accessibility of the socket.\n\nAbstract sockets automatically disappear when all open references to the socket are closed.\n\nThe abstract socket namespace is a nonportable Linux extension.\n"
                    },
                    {
                        "name": "Socket options",
                        "content": "For historical reasons, these socket options are specified with a SOLSOCKET type even though\nthey are AFUNIX specific.  They can be set with setsockopt(2) and read with getsockopt(2) by\nspecifying SOLSOCKET as the socket family.\n\nSOPASSCRED\nEnabling this socket option causes receipt of the credentials of the  sending  process\nin  an  SCMCREDENTIALS  ancillary message in each subsequently received message.  The\nreturned credentials are those specified by the sender using SCMCREDENTIALS, or a de‐\nfault  that  includes the sender's PID, real user ID, and real group ID, if the sender\ndid not specify SCMCREDENTIALS ancillary data.\n\nWhen this option is set and the socket is not yet connected, a unique name in the  ab‐\nstract namespace will be generated automatically.\n\nThe value given as an argument to setsockopt(2) and returned as the result of getsock‐‐\nopt(2) is an integer boolean flag.\n\nSOPASSSEC\nEnables receiving of the SELinux security label of the peer  socket  in  an  ancillary\nmessage of type SCMSECURITY (see below).\n\nThe value given as an argument to setsockopt(2) and returned as the result of getsock‐‐\nopt(2) is an integer boolean flag.\n\nThe SOPASSSEC option is supported  for  UNIX  domain  datagram  sockets  since  Linux\n2.6.18; support for UNIX domain stream sockets was added in Linux 4.2.\n\nSOPEEKOFF\nSee socket(7).\n\nSOPEERCRED\nThis  read-only socket option returns the credentials of the peer process connected to\nthis socket.  The returned credentials are those that were in effect at  the  time  of\nthe call to connect(2) or socketpair(2).\n\nThe  argument  to  getsockopt(2)  is  a  pointer  to  a  ucred  structure;  define the\nGNUSOURCE feature test macro  to  obtain  the  definition  of  that  structure  from\n<sys/socket.h>.\n\nThe  use  of this option is possible only for connected AFUNIX stream sockets and for\nAFUNIX stream and datagram socket pairs created using socketpair(2).\n\nSOPEERSEC\nThis read-only socket option returns the security context of the peer socket connected\nto  this  socket.   By  default,  this will be the same as the security context of the\nprocess that created the peer socket unless overridden by the policy or by  a  process\nwith the required permissions.\n\nThe  argument  to  getsockopt(2)  is  a pointer to a buffer of the specified length in\nbytes into which the security context string will be copied.  If the buffer length  is\nless  than  the  length of the security context string, then getsockopt(2) returns -1,\nsets errno to ERANGE, and returns the required length via optlen.  The  caller  should\nallocate  at least NAMEMAX bytes for the buffer initially, although this is not guar‐\nanteed to be sufficient.  Resizing the buffer to the returned length and retrying  may\nbe necessary.\n\nThe  security  context string may include a terminating null character in the returned\nlength, but is not guaranteed to do so: a security context \"foo\" might be  represented\nas  either {'f','o','o'} of length 3 or {'f','o','o','\\0'} of length 4, which are con‐\nsidered to be interchangeable.  The string is printable, does not  contain  non-termi‐\nnating  null  characters,  and is in an unspecified encoding (in particular, it is not\nguaranteed to be ASCII or UTF-8).\n\nThe use of this option for sockets in the AFUNIX address family  is  supported  since\nLinux  2.6.2  for  connected  stream sockets, and since Linux 4.18 also for stream and\ndatagram socket pairs created using socketpair(2).\n"
                    },
                    {
                        "name": "Autobind feature",
                        "content": "If a bind(2) call specifies addrlen as sizeof(safamilyt), or the SOPASSCRED socket  option\nwas  specified  for  a socket that was not explicitly bound to an address, then the socket is\nautobound to an abstract address.  The address consists of a null byte followed by 5 bytes in\nthe  character set [0-9a-f].  Thus, there is a limit of 2^20 autobind addresses.  (From Linux\n2.1.15, when the autobind feature was added, 8 bytes were used, and the limit was  thus  2^32\nautobind addresses.  The change to 5 bytes came in Linux 2.3.15.)\n"
                    },
                    {
                        "name": "Sockets API",
                        "content": "The  following  paragraphs  describe  domain-specific details and unsupported features of the\nsockets API for UNIX domain sockets on Linux.\n\nUNIX domain sockets do not support the transmission of out-of-band data (the MSGOOB flag for\nsend(2) and recv(2)).\n\nThe send(2) MSGMORE flag is not supported by UNIX domain sockets.\n\nBefore  Linux 3.4, the use of MSGTRUNC in the flags argument of recv(2) was not supported by\nUNIX domain sockets.\n\nThe SOSNDBUF socket option does have an effect for UNIX domain sockets,  but  the  SORCVBUF\noption  does  not.   For  datagram sockets, the SOSNDBUF value imposes an upper limit on the\nsize of outgoing datagrams.  This limit is calculated as the doubled (see  socket(7))  option\nvalue less 32 bytes used for overhead.\n"
                    },
                    {
                        "name": "Ancillary messages",
                        "content": "Ancillary data is sent and received using sendmsg(2) and recvmsg(2).  For historical reasons,\nthe ancillary message types listed below are specified with a  SOLSOCKET  type  even  though\nthey  are  AFUNIX specific.  To send them, set the cmsglevel field of the struct cmsghdr to\nSOLSOCKET and the cmsgtype field to the type.  For more information, see cmsg(3).\n\nSCMRIGHTS\nSend or receive a set of open file descriptors from another process.  The data portion\ncontains an integer array of the file descriptors.\n\nCommonly,  this  operation  is  referred  to as \"passing a file descriptor\" to another\nprocess.  However, more accurately, what is being passed is a  reference  to  an  open\nfile  description (see open(2)), and in the receiving process it is likely that a dif‐\nferent file descriptor number will be used.  Semantically, this operation  is  equiva‐\nlent  to  duplicating (dup(2)) a file descriptor into the file descriptor table of an‐\nother process.\n\nIf the buffer used to receive the ancillary data containing file  descriptors  is  too\nsmall  (or is absent), then the ancillary data is truncated (or discarded) and the ex‐\ncess file descriptors are automatically closed in the receiving process.\n\nIf the number of file descriptors received in  the  ancillary  data  would  cause  the\nprocess to exceed its RLIMITNOFILE resource limit (see getrlimit(2)), the excess file\ndescriptors are automatically closed in the receiving process.\n\nThe kernel constant SCMMAXFD defines a limit on the number of  file  descriptors  in\nthe  array.   Attempting  to send an array larger than this limit causes sendmsg(2) to\nfail with the error EINVAL.  SCMMAXFD has the value 253 (or 255  in  kernels  before\n2.6.38).\n\nSCMCREDENTIALS\nSend  or  receive UNIX credentials.  This can be used for authentication.  The creden‐\ntials are passed as a struct ucred ancillary message.  This structure  is  defined  in\n<sys/socket.h> as follows:\n\nstruct ucred {\npidt pid;    /* Process ID of the sending process */\nuidt uid;    /* User ID of the sending process */\ngidt gid;    /* Group ID of the sending process */\n};\n\nSince  glibc 2.8, the GNUSOURCE feature test macro must be defined (before including\nany header files) in order to obtain the definition of this structure.\n\nThe credentials which the sender specifies are checked by the  kernel.   A  privileged\nprocess is allowed to specify values that do not match its own.  The sender must spec‐\nify its own process ID (unless it has the capability CAPSYSADMIN, in which case  the\nPID of any existing process may be specified), its real user ID, effective user ID, or\nsaved set-user-ID (unless it has CAPSETUID), and its real group ID,  effective  group\nID, or saved set-group-ID (unless it has CAPSETGID).\n\nTo  receive  a  struct  ucred  message,  the SOPASSCRED option must be enabled on the\nsocket.\n\nSCMSECURITY\nReceive the SELinux security context (the security label) of the peer socket.  The re‐\nceived  ancillary  data  is  a null-terminated string containing the security context.\nThe receiver should allocate at least NAMEMAX bytes in the data portion of the ancil‐\nlary message for this data.\n\nTo  receive  the security context, the SOPASSSEC option must be enabled on the socket\n(see above).\n\nWhen sending ancillary data with sendmsg(2), only one item of each of the above types may  be\nincluded in the sent message.\n\nAt least one byte of real data should be sent when sending ancillary data.  On Linux, this is\nrequired to successfully send ancillary data over a UNIX domain stream socket.  When  sending\nancillary  data  over a UNIX domain datagram socket, it is not necessary on Linux to send any\naccompanying real data.  However, portable applications should also include at least one byte\nof real data when sending ancillary data over a datagram socket.\n\nWhen  receiving from a stream socket, ancillary data forms a kind of barrier for the received\ndata.  For example, suppose that the sender transmits as follows:\n\n1. sendmsg(2) of four bytes, with no ancillary data.\n2. sendmsg(2) of one byte, with ancillary data.\n3. sendmsg(2) of four bytes, with no ancillary data.\n\nSuppose that the receiver now performs recvmsg(2) calls each with a buffer size of 20  bytes.\nThe  first  call  will  receive five bytes of data, along with the ancillary data sent by the\nsecond sendmsg(2) call.  The next call will receive the remaining four bytes of data.\n\nIf the space allocated for receiving incoming ancillary data is too small then the  ancillary\ndata  is  truncated to the number of headers that will fit in the supplied buffer (or, in the\ncase of an SCMRIGHTS file descriptor list, the list of file descriptors may  be  truncated).\nIf  no buffer is provided for incoming ancillary data (i.e., the msgcontrol field of the ms‐\nghdr structure supplied to recvmsg(2) is NULL), then the  incoming  ancillary  data  is  dis‐\ncarded.   In  both of these cases, the MSGCTRUNC flag will be set in the msg.msgflags value\nreturned by recvmsg(2).\n"
                    },
                    {
                        "name": "Ioctls",
                        "content": "The following ioctl(2) calls return information in value.  The correct syntax is:\n\nint value;\nerror = ioctl(unixsocket, ioctltype, &value);\n\nioctltype can be:\n\nSIOCINQ\nFor SOCKSTREAM sockets, this call returns the number of unread bytes in  the  receive\nbuffer.   The  socket  must not be in LISTEN state, otherwise an error (EINVAL) is re‐\nturned.  SIOCINQ is defined in <linux/sockios.h>.  Alternatively, you can use the syn‐\nonymous  FIONREAD,  defined  in  <sys/ioctl.h>.   For SOCKDGRAM sockets, the returned\nvalue is the same as for Internet domain datagram sockets; see udp(7).\n"
                    }
                ]
            },
            "ERRORS": {
                "content": "EADDRINUSE\nThe specified local address is already in use or the filesystem socket object  already\nexists.\n\nEBADF  This  error  can occur for sendmsg(2) when sending a file descriptor as ancillary data\nover a UNIX domain socket (see the description of SCMRIGHTS,  above),  and  indicates\nthat  the  file  descriptor number that is being sent is not valid (e.g., it is not an\nopen file descriptor).\n\nECONNREFUSED\nThe remote address specified by connect(2) was not a listening socket.  This error can\nalso occur if the target pathname is not a socket.\n\nECONNRESET\nRemote socket was unexpectedly closed.\n\nEFAULT User memory address was not valid.\n\nEINVAL Invalid  argument  passed.  A common cause is that the value AFUNIX was not specified\nin the suntype field of passed addresses, or the socket was in an invalid  state  for\nthe applied operation.\n\nEISCONN\nconnect(2)  called on an already connected socket or a target address was specified on\na connected socket.\n\nENOENT The pathname in the remote address specified to connect(2) did not exist.\n\nENOMEM Out of memory.\n\nENOTCONN\nSocket operation needs a target address, but the socket is not connected.\n\nEOPNOTSUPP\nStream operation called on non-stream oriented socket or tried to use the  out-of-band\ndata option.\n\nEPERM  The sender passed invalid credentials in the struct ucred.\n\nEPIPE  Remote  socket  was closed on a stream socket.  If enabled, a SIGPIPE is sent as well.\nThis can be avoided by passing the MSGNOSIGNAL flag to send(2) or sendmsg(2).\n\nEPROTONOSUPPORT\nPassed protocol is not AFUNIX.\n\nEPROTOTYPE\nRemote socket does not match the local socket type (SOCKDGRAM versus SOCKSTREAM).\n\nESOCKTNOSUPPORT\nUnknown socket type.\n\nESRCH  While sending an  ancillary  message  containing  credentials  (SCMCREDENTIALS),  the\ncaller specified a PID that does not match any existing process.\n\nETOOMANYREFS\nThis  error  can occur for sendmsg(2) when sending a file descriptor as ancillary data\nover a UNIX domain socket (see the description of SCMRIGHTS, above).   It  occurs  if\nthe  number  of  \"in-flight\" file descriptors exceeds the RLIMITNOFILE resource limit\nand the caller does not have the CAPSYSRESOURCE capability.  An in-flight  file  de‐\nscriptor  is  one that has been sent using sendmsg(2) but has not yet been accepted in\nthe recipient process using recvmsg(2).\n\nThis error is diagnosed since mainline Linux 4.5 (and in some earlier kernel  versions\nwhere  the  fix  has been backported).  In earlier kernel versions, it was possible to\nplace an unlimited number of file descriptors in flight, by sending each file descrip‐\ntor  with sendmsg(2) and then closing the file descriptor so that it was not accounted\nagainst the RLIMITNOFILE resource limit.\n\nOther errors can be generated by the generic socket layer or by the filesystem while generat‐\ning a filesystem socket object.  See the appropriate manual pages for more information.\n",
                "subsections": []
            },
            "VERSIONS": {
                "content": "SCMCREDENTIALS  and  the abstract namespace were introduced with Linux 2.2 and should not be\nused in portable programs.  (Some BSD-derived systems also support  credential  passing,  but\nthe implementation details differ.)\n",
                "subsections": []
            },
            "NOTES": {
                "content": "Binding  to  a socket with a filename creates a socket in the filesystem that must be deleted\nby the caller when it is no longer needed (using unlink(2)).  The usual UNIX close-behind se‐\nmantics  apply;  the  socket can be unlinked at any time and will be finally removed from the\nfilesystem when the last reference to it is closed.\n\nTo pass file descriptors or credentials over a SOCKSTREAM socket, you must to  send  or  re‐\nceive at least one byte of nonancillary data in the same sendmsg(2) or recvmsg(2) call.\n\nUNIX domain stream sockets do not support the notion of out-of-band data.\n",
                "subsections": []
            },
            "BUGS": {
                "content": "When  binding a socket to an address, Linux is one of the implementations that appends a null\nterminator if none is supplied in sunpath.  In most cases this is  unproblematic:  when  the\nsocket  address  is  retrieved, it will be one byte longer than that supplied when the socket\nwas bound.  However, there is one case where confusing behavior can result: if  108  non-null\nbytes are supplied when a socket is bound, then the addition of the null terminator takes the\nlength of the pathname beyond sizeof(sunpath).  Consequently, when retrieving the socket ad‐\ndress  (for example, via accept(2)), if the input addrlen argument for the retrieving call is\nspecified as sizeof(struct sockaddrun), then the returned address  structure  won't  have  a\nnull terminator in sunpath.\n\nIn  addition, some implementations don't require a null terminator when binding a socket (the\naddrlen argument is used to determine the length of sunpath) and when the socket address  is\nretrieved on these implementations, there is no null terminator in sunpath.\n\nApplications  that  retrieve  socket  addresses can (portably) code to handle the possibility\nthat there is no null terminator in sunpath by respecting the fact that the number of  valid\nbytes in the pathname is:\n\nstrnlen(addr.sunpath, addrlen - offsetof(sockaddrun, sunpath))\n\nAlternatively,  an application can retrieve the socket address by allocating a buffer of size\nsizeof(struct sockaddrun)+1 that is zeroed out before the retrieval.   The  retrieving  call\ncan specify addrlen as sizeof(struct sockaddrun), and the extra zero byte ensures that there\nwill be a null terminator for the string returned in sunpath:\n\nvoid *addrp;\n\naddrlen = sizeof(struct sockaddrun);\naddrp = malloc(addrlen + 1);\nif (addrp == NULL)\n/* Handle error */ ;\nmemset(addrp, 0, addrlen + 1);\n\nif (getsockname(sfd, (struct sockaddr *) addrp, &addrlen)) == -1)\n/* handle error */ ;\n\nprintf(\"sunpath = %s\\n\", ((struct sockaddrun *) addrp)->sunpath);\n\nThis sort of messiness can be avoided if it is guaranteed that the applications  that  create\npathname sockets follow the rules outlined above under Pathname sockets.\n",
                "subsections": []
            },
            "EXAMPLES": {
                "content": "The  following  code  demonstrates the use of sequenced-packet sockets for local interprocess\ncommunication.  It consists of two programs.  The server program waits for a connection  from\nthe  client  program.   The  client sends each of its command-line arguments in separate mes‐\nsages.  The server treats the incoming messages as integers and adds  them  up.   The  client\nsends  the  command  string \"END\".  The server sends back a message containing the sum of the\nclient's integers.  The client prints the sum and exits.   The  server  waits  for  the  next\nclient  to  connect.  To stop the server, the client is called with the command-line argument\n\"DOWN\".\n\nThe following output was recorded while running the server in the background  and  repeatedly\nexecuting  the client.  Execution of the server program ends when it receives the \"DOWN\" com‐\nmand.\n",
                "subsections": [
                    {
                        "name": "Example output",
                        "content": "$ ./server &\n[1] 25887\n$ ./client 3 4\nResult = 7\n$ ./client 11 -5\nResult = 6\n$ ./client DOWN\nResult = 0\n[1]+  Done                    ./server\n$\n"
                    },
                    {
                        "name": "Program source",
                        "content": "/*\n* File connection.h\n*/\n\n#define SOCKETNAME \"/tmp/9Lq7BNBnBycd6nxy.socket\"\n#define BUFFERSIZE 12\n\n/*\n* File server.c\n*/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys/socket.h>\n#include <sys/un.h>\n#include <unistd.h>\n#include \"connection.h\"\n\nint\nmain(int argc, char *argv[])\n{\nstruct sockaddrun name;\nint downflag = 0;\nint ret;\nint connectionsocket;\nint datasocket;\nint result;\nchar buffer[BUFFERSIZE];\n\n/* Create local socket. */\n\nconnectionsocket = socket(AFUNIX, SOCKSEQPACKET, 0);\nif (connectionsocket == -1) {\nperror(\"socket\");\nexit(EXITFAILURE);\n}\n\n/*\n* For portability clear the whole structure, since some\n* implementations have additional (nonstandard) fields in\n* the structure.\n*/\n\nmemset(&name, 0, sizeof(name));\n\n/* Bind socket to socket name. */\n\nname.sunfamily = AFUNIX;\nstrncpy(name.sunpath, SOCKETNAME, sizeof(name.sunpath) - 1);\n\nret = bind(connectionsocket, (const struct sockaddr *) &name,\nsizeof(name));\nif (ret == -1) {\nperror(\"bind\");\nexit(EXITFAILURE);\n}\n\n/*\n* Prepare for accepting connections. The backlog size is set\n* to 20. So while one request is being processed other requests\n* can be waiting.\n*/\n\nret = listen(connectionsocket, 20);\nif (ret == -1) {\nperror(\"listen\");\nexit(EXITFAILURE);\n}\n\n/* This is the main loop for handling connections. */\n\nfor (;;) {\n\n/* Wait for incoming connection. */\n\ndatasocket = accept(connectionsocket, NULL, NULL);\nif (datasocket == -1) {\nperror(\"accept\");\nexit(EXITFAILURE);\n}\n\nresult = 0;\nfor (;;) {\n\n/* Wait for next data packet. */\n\nret = read(datasocket, buffer, sizeof(buffer));\nif (ret == -1) {\nperror(\"read\");\nexit(EXITFAILURE);\n}\n\n/* Ensure buffer is 0-terminated. */\n\nbuffer[sizeof(buffer) - 1] = 0;\n\n/* Handle commands. */\n\nif (!strncmp(buffer, \"DOWN\", sizeof(buffer))) {\ndownflag = 1;\nbreak;\n}\n\nif (!strncmp(buffer, \"END\", sizeof(buffer))) {\nbreak;\n}\n\n/* Add received summand. */\n\nresult += atoi(buffer);\n}\n\n/* Send result. */\n\nsprintf(buffer, \"%d\", result);\nret = write(datasocket, buffer, sizeof(buffer));\nif (ret == -1) {\nperror(\"write\");\nexit(EXITFAILURE);\n}\n\n/* Close socket. */\n\nclose(datasocket);\n\n/* Quit on DOWN command. */\n\nif (downflag) {\nbreak;\n}\n}\n\nclose(connectionsocket);\n\n/* Unlink the socket. */\n\nunlink(SOCKETNAME);\n\nexit(EXITSUCCESS);\n}\n\n/*\n* File client.c\n*/\n\n#include <errno.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys/socket.h>\n#include <sys/un.h>\n#include <unistd.h>\n#include \"connection.h\"\n\nint\nmain(int argc, char *argv[])\n{\nstruct sockaddrun addr;\nint ret;\nint datasocket;\nchar buffer[BUFFERSIZE];\n\n/* Create local socket. */\n\ndatasocket = socket(AFUNIX, SOCKSEQPACKET, 0);\nif (datasocket == -1) {\nperror(\"socket\");\nexit(EXITFAILURE);\n}\n\n/*\n* For portability clear the whole structure, since some\n* implementations have additional (nonstandard) fields in\n* the structure.\n*/\n\nmemset(&addr, 0, sizeof(addr));\n\n/* Connect socket to socket address */\n\naddr.sunfamily = AFUNIX;\nstrncpy(addr.sunpath, SOCKETNAME, sizeof(addr.sunpath) - 1);\n\nret = connect(datasocket, (const struct sockaddr *) &addr,\nsizeof(addr));\nif (ret == -1) {\nfprintf(stderr, \"The server is down.\\n\");\nexit(EXITFAILURE);\n}\n\n/* Send arguments. */\n\nfor (int i = 1; i < argc; ++i) {\nret = write(datasocket, argv[i], strlen(argv[i]) + 1);\nif (ret == -1) {\nperror(\"write\");\nbreak;\n}\n}\n\n/* Request result. */\n\nstrcpy(buffer, \"END\");\nret = write(datasocket, buffer, strlen(buffer) + 1);\nif (ret == -1) {\nperror(\"write\");\nexit(EXITFAILURE);\n}\n\n/* Receive result. */\n\nret = read(datasocket, buffer, sizeof(buffer));\nif (ret == -1) {\nperror(\"read\");\nexit(EXITFAILURE);\n}\n\n/* Ensure buffer is 0-terminated. */\n\nbuffer[sizeof(buffer) - 1] = 0;\n\nprintf(\"Result = %s\\n\", buffer);\n\n/* Close socket. */\n\nclose(datasocket);\n\nexit(EXITSUCCESS);\n}\n\nFor an example of the use of SCMRIGHTS see cmsg(3).\n"
                    }
                ]
            },
            "SEE ALSO": {
                "content": "recvmsg(2), sendmsg(2), socket(2), socketpair(2), cmsg(3),  capabilities(7),  credentials(7),\nsocket(7), udp(7)\n",
                "subsections": []
            },
            "COLOPHON": {
                "content": "This  page  is  part  of  release  5.10 of the Linux man-pages project.  A description of the\nproject, information about reporting bugs, and the latest version of this page, can be  found\nat https://www.kernel.org/doc/man-pages/.\n\n\n\nLinux                                        2020-11-01                                      UNIX(7)",
                "subsections": []
            }
        }
    }
}