unix (7) - Linux Manuals
unix: sockets for local interprocess communication
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 datagrams); and (since Linux 2.6.4) SOCK_SEQPACKET, for a sequenced-packet socket that is connection-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 processes using ancillary data.
Address format
A UNIX domain socket address is represented in the following structure:
struct sockaddr_un {
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),
connect(2),
and
sendto(2))
take a
sockaddr_un
argument as input.
Some other system calls (for example,
getsockname(2),
getpeername(2),
recvfrom(2),
and
accept(2))
return an argument of this type.
Three types of address are distinguished in the
sockaddr_un
structure:
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),
recvfrom(2),
getsockname(2),
getpeername(2))
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 indicate 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.)
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).
The owner, group, and permissions of a pathname socket can be changed (using
chown(2)
and
chmod(2)).
Abstract sockets automatically disappear when all open references
to the socket are closed.
The abstract socket namespace is a nonportable Linux extension.
UNIX domain sockets do not support the transmission of
out-of-band data (the
MSG_OOB
flag for
send(2)
and
recv(2)).
The
send(2)
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)
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))
option value less 32 bytes used for overhead.
When sending ancillary data with
sendmsg(2),
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:
Suppose that the receiver now performs
recvmsg(2)
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)
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
msghdr
structure supplied to
recvmsg(2)
is NULL),
then the incoming ancillary data is discarded.
In both of these cases, the
MSG_CTRUNC
flag will be set in the
msg.msg_flags
value returned by
recvmsg(2).
ioctl_type
can be:
Other errors can be generated by the generic socket layer or
by the filesystem while generating a filesystem socket object.
See the appropriate manual pages for more information.
To pass file descriptors or credentials over a
SOCK_STREAM
socket, you must
to send or receive at least one byte of nonancillary data in the same
sendmsg(2)
or
recvmsg(2)
call.
UNIX domain stream sockets do not support the notion of out-of-band data.
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:
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)
if (getsockname(sfd, (struct sockaddr *) addrp, &addrlen)) == -1)
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.
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" command.
#define SOCKET_NAME "/tmp/9Lq7BNBnBycd6nxy.socket"
#define BUFFER_SIZE 12
/*
#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[])
{
Pathname sockets
When binding a socket to a pathname, a few rules should be observed
for maximum portability and ease of coding:
offsetof(struct sockaddr_un, sun_path)+strlen(addr.sun_path)+1
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.
Abstract sockets
Socket permissions have no meaning for abstract sockets:
the process
umask(2)
has no effect when binding an abstract socket,
and changing the ownership and permissions of the object (via
fchown(2)
and
fchmod(2))
has no effect on the accessibility of the socket.
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)
and read with
getsockopt(2)
by specifying
SOL_SOCKET
as the socket family.
Autobind feature
If a
bind(2)
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.
Ancillary messages
Ancillary data is sent and received using
sendmsg(2)
and
recvmsg(2).
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).
Ioctls
The following
ioctl(2)
calls return information in
value.
The correct syntax is:
int value;
error = ioctl(unix_socket, ioctl_type, &value);
ERRORS
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)).
The usual UNIX close-behind semantics 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.
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 address
(for example, via
accept(2)),
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.
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 messages.
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".
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
*/
* File server.c
*/