You are on page 1of 23

SOCKET(2) Linux Programmer’s Manual SOCKET(2)

NAME
socket − create an endpoint for communication

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

int socket(int domain, int type, int protocol);

DESCRIPTION
Socket creates an endpoint for communication and returns a
descriptor.

The domain parameter specifies a communication domain;


this selects the protocol family which will be used for
communication. These families are defined in
<sys/socket.h>. The currently understood formats include:

Name Purpose Man page


PF_UNIX,PF_LOCAL Local communication unix(7)
PF_INET IPv4 Internet protocols ip(7)
PF_INET6 IPv6 Internet protocols
PF_IPX IPX − Novell protocols
PF_NETLINK Kernel user interface device netlink(7)
PF_X25 ITU−T X.25 / ISO−8208 protocol x25(7)
PF_AX25 Amateur radio AX.25 protocol
PF_ATMPVC Access to raw ATM PVCs
PF_APPLETALK Appletalk ddp(7)
PF_PACKET Low level packet interface packet(7)

The socket has the indicated type, which specifies the


communication semantics. Currently defined types are:

SOCK_STREAM
Provides sequenced, reliable, two−way, connection−
based byte streams. An out−of−band data transmis-
sion mechanism may be supported.

SOCK_DGRAM
Supports datagrams (connectionless, unreliable mes-
sages of a fixed maximum length).

SOCK_SEQPACKET
Provides a sequenced, reliable, two−way connection−
based data transmission path for datagrams of fixed
maximum length; a consumer is required to read an
entire packet with each read system call.

SOCK_RAW
Provides raw network protocol access.

SOCK_RDM
Provides a reliable datagram layer that does not
guarantee ordering.

Linux Man Page 24 Apr 1999 1


SOCKET(2) Linux Programmer’s Manual SOCKET(2)

SOCK_PACKET
Obsolete and should not be used in new programs;
see packet(7).

Some socket types may not be implemented by all protocol


families; for example, SOCK_SEQPACKET is not implemented
for AF_INET.

The protocol specifies a particular protocol to be used


with the socket. Normally only a single protocol exists
to support a particular socket type within a given proto-
col family. However, it is possible that many protocols
may exist, in which case a particular protocol must be
specified in this manner. The protocol number to use is
specific to the "communication domain" in which communica-
tion is to take place; see protocols(5). See getpro-
toent(3) on how to map protocol name strings to protocol
numbers.

Sockets of type SOCK_STREAM are full−duplex byte streams,


similar to pipes. They do not preserve record boundaries.
A stream socket must be in a connected state before any
data may be sent or received on it. A connection to
another socket is created with a connect(2) call. Once
connected, data may be transferred using read(2) and
write(2) calls or some variant of the send(2) and recv(2)
calls. When a session has been completed a close(2) may
be performed. Out−of−band data may also be transmitted as
described in send(2) and received as described in recv(2).

The communications protocols which implement a SOCK_STREAM


ensure that data is not lost or duplicated. If a piece of
data for which the peer protocol has buffer space cannot
be successfully transmitted within a reasonable length of
time, then the connection is considered to be dead. When
SO_KEEPALIVE is enabled on the socket the protocol checks
in a protocol−specific manner if the other end is still
alive. A SIGPIPE signal is raised if a process sends or
receives on a broken stream; this causes naive processes,
which do not handle the signal, to exit. SOCK_SEQPACKET
sockets employ the same system calls as SOCK_STREAM sock-
ets. The only difference is that read(2) calls will
return only the amount of data requested, and any remain-
ing in the arriving packet will be discarded. Also all
message boundaries in incoming datagrams are preserved.

SOCK_DGRAM and SOCK_RAW sockets allow sending of datagrams


to correspondents named in send(2) calls. Datagrams are
generally received with recvfrom(2), which returns the
next datagram with its return address.

SOCK_PACKET is an obsolete socket type to receive raw


packets directly from the device driver. Use packet(7)
instead.

Linux Man Page 24 Apr 1999 2


SOCKET(2) Linux Programmer’s Manual SOCKET(2)

An fcntl(2) call with the the F_SETOWN argument can be


used to specify a process group to receive a SIGURG signal
when the out−of−band data arrives or SIGPIPE signal when a
SOCK_STREAM connection breaks unexpectedly. It may also
be used to set the process or process group that receives
the I/O and asynchronous notification of I/O events via
SIGIO. Using F_SETOWN is equivalent to an ioctl(2) call
with the SIOSETOWN argument.

When the network signals an error condition to the proto-


col module (e.g. using a ICMP message for IP) the pending
error flag is set for the socket. The next operation on
this socket will return the error code of the pending
error. For some protocols it is possible to enable a per−
socket error queue to retrieve detailed information about
the error; see IP_RECVERR in ip(7).

The operation of sockets is controlled by socket level


options. These options are defined in <sys/socket.h>.
Setsockopt(2) and getsockopt(2) are used to set and get
options, respectively.

RETURN VALUE
−1 is returned if an error occurs; otherwise the return
value is a descriptor referencing the socket.

ERRORS
EPROTONOSUPPORT
The protocol type or the specified protocol is not
supported within this domain.

ENFILE Not enough kernel memory to allocate a new socket


structure.

EMFILE Process file table overflow.

EACCES Permission to create a socket of the specified type


and/or protocol is denied.

ENOBUFS or ENOMEM
Insufficient memory is available. The socket can-
not be created until sufficient resources are
freed.

EINVAL Unknown protocol, or protocol family not available.

Other errors may be generated by the underlying protocol


modules.

CONFORMING TO
4.4BSD (the socket function call appeared in 4.2BSD). Gen-
erally portable to/from non−BSD systems supporting clones
of the BSD socket layer (including System V variants).

Linux Man Page 24 Apr 1999 3


SOCKET(2) Linux Programmer’s Manual SOCKET(2)

NOTE
The manifest constants used under BSD 4.* for protocol
families are PF_UNIX, PF_INET, etc., while AF_UNIX etc.
are used for address families. However, already the BSD
man page promises: "The protocol family generally is the
same as the address family", and subsequent standards use
AF_* everywhere.

BUGS
SOCK_UUCP is not implemented yet.

SEE ALSO
accept(2), bind(2), connect(2), getprotoent(3), getsock-
name(2), getsockopt(2), ioctl(2), listen(2), read(2),
recv(2), select(2), send(2), shutdown(2), socketpair(2),
write(2)

"An Introductory 4.3 BSD Interprocess Communication Tuto-


rial" is reprinted in UNIX Programmer’s Supplementary Doc-
uments Volume 1.

"BSD Interprocess Communication Tutorial" is reprinted in


UNIX Programmer’s Supplementary Documents Volume 1.

Linux Man Page 24 Apr 1999 4


BIND(2) Linux Programmer’s Manual BIND(2)

NAME
bind − bind a name to a socket

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

int bind(int sockfd, struct sockaddr *my_addr, socklen_t


addrlen);

DESCRIPTION
bind gives the socket sockfd the local address my_addr.
my_addr is addrlen bytes long. Traditionally, this is
called "assigning a name to a socket." When a socket is
created with socket(2), it exists in a name space (address
family) but has no name assigned.

It is normally necessary to assign a local address using


bind before a SOCK_STREAM socket may receive connections
(see accept(2)).

NOTES
The rules used in name binding vary between address fami-
lies. Consult the manual entries in Section 7 for
detailed information. For AF_INET see ip(7), for AF_UNIX
see unix(7), for AF_APPLETALK see ddp(7), for AF_PACKET
see packet(7), for AF_X25 see x25(7) and for AF_NETLINK
see netlink(7).

RETURN VALUE
On success, zero is returned. On error, −1 is returned,
and errno is set appropriately.

ERRORS
EBADF sockfd is not a valid descriptor.

EINVAL The socket is already bound to an address. This


may change in the future: see linux/unix/sock.c for
details.

EACCES The address is protected, and the user is not the


super−user.

ENOTSOCK
Argument is a descriptor for a file, not a socket.

The following errors are specific to UNIX domain (AF_UNIX)


sockets:

EINVAL The addrlen is wrong, or the socket was not in the


AF_UNIX family.

EROFS The socket inode would reside on a read−only file

Linux 2.2 3 Oct 1998 1


BIND(2) Linux Programmer’s Manual BIND(2)

system.

EFAULT my_addr points outside the user’s accessible


address space.

ENAMETOOLONG
my_addr is too long.

ENOENT The file does not exist.

ENOMEM Insufficient kernel memory was available.

ENOTDIR
A component of the path prefix is not a directory.

EACCES Search permission is denied on a component of the


path prefix.

ELOOP Too many symbolic links were encountered in resolv-


ing my_addr.

BUGS
The transparent proxy options are not described.

CONFORMING TO
SVr4, 4.4BSD (the bind function first appeared in BSD
4.2). SVr4 documents additional EADDRNOTAVAIL, EADDRI-
NUSE, and ENOSR general error conditions, and additional
EIO, EISDIR and EROFS Unix−domain error conditions.

NOTE
The third argument of bind is in reality an int (and this
is what BSD 4.* and libc4 and libc5 have). Some POSIX
confusion resulted in the present socklen_t. The draft
standard has not been adopted yet, but glibc2 already fol-
lows it and also has socklen_t. See also accept(2).

SEE ALSO
accept(2), connect(2), listen(2), socket(2), getsock-
name(2), ip(7), socket(7)

Linux 2.2 3 Oct 1998 2


LISTEN(2) Linux Programmer’s Manual LISTEN(2)

NAME
listen − listen for connections on a socket

SYNOPSIS
#include <sys/socket.h>

int listen(int s, int backlog);

DESCRIPTION
To accept connections, a socket is first created with
socket(2), a willingness to accept incoming connections
and a queue limit for incoming connections are specified
with listen, and then the connections are accepted with
accept(2). The listen call applies only to sockets of
type SOCK_STREAM or SOCK_SEQPACKET.

The backlog parameter defines the maximum length the queue


of pending connections may grow to. If a connection
request arrives with the queue full the client may receive
an error with an indication of ECONNREFUSED or, if the
underlying protocol supports retransmission, the request
may be ignored so that retries succeed.

NOTES
The behaviour of the backlog parameter on TCP sockets
changed with Linux 2.2. Now it specifies the queue length
for completely established sockets waiting to be accepted,
instead of the number of incomplete connection requests.
The maximum length of the queue for incomplete sockets can
be set using the tcp_max_syn_backlog sysctl. When syn-
cookies are enabled there is no logical maximum length and
this sysctl setting is ignored. See tcp(7) for more
information.

RETURN VALUE
On success, zero is returned. On error, −1 is returned,
and errno is set appropriately.

ERRORS
EBADF The argument s is not a valid descriptor.

ENOTSOCK
The argument s is not a socket.

EOPNOTSUPP
The socket is not of a type that supports the lis-
ten operation.

CONFORMING TO
Single Unix, 4.4BSD, POSIX 1003.1g draft. The listen func-
tion call first appeared in 4.2BSD.

BSD Man Page 23 July 1993 1


LISTEN(2) Linux Programmer’s Manual LISTEN(2)

BUGS
If the socket is of type AF_INET, and the backlog argument
is greater than the constant SOMAXCONN (128 in Linux 2.0 &
2.2), it is silently truncated to SOMAXCONN. Don’t rely
on this value in portable applications since BSD (and some
BSD−derived systems) limit the backlog to 5.

SEE ALSO
accept(2), connect(2), socket(2)

BSD Man Page 23 July 1993 2


ACCEPT(2) Linux Programmer’s Manual ACCEPT(2)

NAME
accept − accept a connection on a socket

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

int accept(int s, struct sockaddr *addr, socklen_t


*addrlen);

DESCRIPTION
The accept function is used with connection−based socket
types (SOCK_STREAM, SOCK_SEQPACKET and SOCK_RDM). It
extracts the first connection request on the queue of
pending connections, creates a new connected socket with
mostly the same properties as s, and allocates a new file
descriptor for the socket, which is returned. The newly
created socket is no longer in the listening state. The
original socket s is unaffected by this call. Note that
any per file descriptor flags (everything that can be set
with the F_SETFL fcntl, like non blocking or async state)
are not inherited across a accept.

The argument s is a socket that has been created with


socket(2), bound to a local address with bind(2), and is
listening for connections after a listen(2).

The argument addr is a pointer to a sockaddr structure.


This structure is filled in with the address of the con-
necting entity, as known to the communications layer. The
exact format of the address passed in the addr parameter
is determined by the socket’s family (see socket(2) and
the respective protocol man pages). The addrlen argument
is a value−result parameter: it should initially contain
the size of the structure pointed to by addr; on return it
will contain the actual length (in bytes) of the address
returned. When addr is NULL nothing is filled in.

If no pending connections are present on the queue, and


the socket is not marked as non−blocking, accept blocks
the caller until a connection is present. If the socket
is marked non−blocking and no pending connections are pre-
sent on the queue, accept returns EAGAIN.

In order to be notified of incoming connections on a


socket, you can use select(2) or poll(2). A readable
event will be delivered when a new connection is attempted
and you may then call accept to get a socket for that con-
nection. Alternatively, you can set the socket to deliver
SIGIO when activity occurs on a socket; see socket(7) for
details.

For certain protocols which require an explicit confirma-


tion, such as DECNet, accept can be thought of as merely

Linux 2.2 Page 7 May 1999 1


ACCEPT(2) Linux Programmer’s Manual ACCEPT(2)

dequeuing the next connection request and not implying


confirmation. Confirmation can be implied by a normal
read or write on the new file descriptor, and rejection
can be implied by closing the new socket. Currently only
DECNet has these semantics on Linux.

NOTES
There may not always be a connection waiting after a SIGIO
is delivered or select(2) or poll(2) return a readability
event because the connection might have been removed by an
asynchronous network error or another thread before accept
is called. If this happens then the call will block wait-
ing for the next connection to arrive. To ensure that
accept never blocks, the passed socket s needs to have the
O_NONBLOCK flag set (see socket(7)).

RETURN VALUE
The call returns −1 on error. If it succeeds, it returns
a non−negative integer that is a descriptor for the
accepted socket.

ERROR HANDLING
Linux accept passes already−pending network errors on the
new socket as an error code from accept. This behaviour
differs from other BSD socket implementations. For reli-
able operation the application should detect the network
errors defined for the protocol after accept and treat
them like EAGAIN by retrying. In case of TCP/IP these are
ENETDOWN, EPROTO, ENOPROTOOPT, EHOSTDOWN, ENONET, EHOSTUN-
REACH, EOPNOTSUPP, and ENETUNREACH.

ERRORS
EAGAIN or EWOULDBLOCK
The socket is marked non−blocking and no connec-
tions are present to be accepted.

EBADF The descriptor is invalid.

ENOTSOCK
The descriptor references a file, not a socket.

EOPNOTSUPP
The referenced socket is not of type SOCK_STREAM.

EFAULT The addr parameter is not in a writable part of the


user address space.

EPERM Firewall rules forbid connection.

ENOBUFS, ENOMEM
Not enough free memory. This often means that the
memory allocation is limited by the socket buffer

Linux 2.2 Page 7 May 1999 2


ACCEPT(2) Linux Programmer’s Manual ACCEPT(2)

limits, not by the system memory, but this is not


100% consistent.

In addition, network errors for the new socket and as


defined for the protocol may be returned. Various Linux
kernels can return other errors such as EMFILE, EINVAL,
ENOSR, ENOBUFS, EPERM, ECONNABORTED, ESOCKTNOSUPPORT,
EPROTONOSUPPORT, ETIMEDOUT, ERESTARTSYS.

CONFORMING TO
SVr4, 4.4BSD (the accept function first appeared in BSD
4.2). The BSD man page documents five possible error
returns (EBADF, ENOTSOCK, EOPNOTSUPP, EWOULDBLOCK,
EFAULT). SUSv2 documents errors EAGAIN, EBADF,
ECONNABORTED, EFAULT, EINTR, EINVAL, EMFILE, ENFILE,
ENOBUFS, ENOMEM, ENOSR, ENOTSOCK, EOPNOTSUPP, EPROTO,
EWOULDBLOCK.

NOTE
The third argument of accept was originally declared as an
‘int *’ (and is that under libc4 and libc5 and on many
other systems like BSD 4.*, SunOS 4, SGI); a POSIX 1003.1g
draft standard wanted to change it into a ‘size_t *’, and
that is what it is for SunOS 5. Later POSIX drafts have
‘socklen_t *’, and so do the Single Unix Specification and
glibc2. Quoting Linus Torvalds: _Any_ sane library _must_
have "socklen_t" be the same size as int. Anything else
breaks any BSD socket layer stuff. POSIX initially _did_
make it a size_t, and I (and hopefully others, but obvi-
ously not too many) complained to them very loudly indeed.
Making it a size_t is completely broken, exactly because
size_t very seldom is the same size as "int" on 64−bit
architectures, for example. And it _has_ to be the same
size as "int" because that’s what the BSD socket interface
is. Anyway, the POSIX people eventually got a clue, and
created "socklen_t". They shouldn’t have touched it in
the first place, but once they did they felt it had to
have a named type for some unfathomable reason (probably
somebody didn’t like losing face over having done the
original stupid thing, so they silently just renamed their
blunder).

SEE ALSO
bind(2), connect(2), listen(2), select(2), socket(2)

Linux 2.2 Page 7 May 1999 3


CONNECT(2) Linux Programmer’s Manual CONNECT(2)

NAME
connect − initiate a connection on a socket

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

int connect(int sockfd, const struct sockaddr *serv_addr,


socklen_t addrlen);

DESCRIPTION
The file descriptor sockfd must refer to a socket. If the
socket is of type SOCK_DGRAM then the serv_addr address is
the address to which datagrams are sent by default, and
the only address from which datagrams are received. If
the socket is of type SOCK_STREAM or SOCK_SEQPACKET, this
call attempts to make a connection to another socket. The
other socket is specified by serv_addr, which is an
address (of length addrlen) in the communications space of
the socket. Each communications space interprets the
serv_addr parameter in its own way.

Generally, connection−based protocol sockets may success-


fully connect only once; connectionless protocol sockets
may use connect multiple times to change their associa-
tion. Connectionless sockets may dissolve the association
by connecting to an address with the sa_family member of
sockaddr set to AF_UNSPEC.

RETURN VALUE
If the connection or binding succeeds, zero is returned.
On error, −1 is returned, and errno is set appropriately.

ERRORS
The following are general socket errors only. There may
be other domain−specific error codes.

EBADF The file descriptor is not a valid index in the


descriptor table.

EFAULT The socket structure address is outside the user’s


address space.

ENOTSOCK
The file descriptor is not associated with a
socket.

EISCONN
The socket is already connected.

ECONNREFUSED
No one listening on the remote address.

Linux 2.2 3 Oct 1998 1


CONNECT(2) Linux Programmer’s Manual CONNECT(2)

ETIMEDOUT
Timeout while attempting connection. The server may
be too busy to accept new connections. Note that
for IP sockets the timeout may be very long when
syncookies are enabled on the server.

ENETUNREACH
Network is unreachable.

EADDRINUSE
Local address is already in use.

EINPROGRESS
The socket is non−blocking and the connection can-
not be completed immediately. It is possible to
select(2) or poll(2) for completion by selecting
the socket for writing. After select indicates
writability, use getsockopt(2) to read the SO_ERROR
option at level SOL_SOCKET to determine whether
connect completed successfully (SO_ERROR is zero)
or unsuccessfully (SO_ERROR is one of the usual
error codes listed here, explaining the reason for
the failure).

EALREADY
The socket is non−blocking and a previous connec-
tion attempt has not yet been completed.

EAGAIN No more free local ports or insufficient entries in


the routing cache. For PF_INET see the
net.ipv4.ip_local_port_range sysctl in ip(7) on how
to increase the number of local ports.

EAFNOSUPPORT
The passed address didn’t have the correct address
family in its sa_family field.

EACCES, EPERM
The user tried to connect to a broadcast address
without having the socket broadcast flag enabled or
the connection request failed because of a local
firewall rule.

CONFORMING TO
SVr4, 4.4BSD (the connect function first appeared in BSD
4.2). SVr4 documents the additional general error codes
EADDRNOTAVAIL, EINVAL, EAFNOSUPPORT, EALREADY, EINTR,
EPROTOTYPE, and ENOSR. It also documents many additional
error conditions not described here.

NOTE
The third argument of connect is in reality an int (and
this is what BSD 4.* and libc4 and libc5 have). Some
POSIX confusion resulted in the present socklen_t. The

Linux 2.2 3 Oct 1998 2


CONNECT(2) Linux Programmer’s Manual CONNECT(2)

draft standard has not been adopted yet, but glibc2


already follows it and also has socklen_t. See also

BUGS
Unconnecting a socket by calling connect with a AF_UNSPEC
address is not yet implemented.

SEE ALSO
accept(2), bind(2), listen(2), socket(2), getsockname(2)

Linux 2.2 3 Oct 1998 3


RECV(2) Linux Programmer’s Manual RECV(2)

NAME
recv, recvfrom, recvmsg − receive a message from a socket

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

int recv(int s, void *buf, size_t len, int flags);

int recvfrom(int s, void *buf, size_t len, int flags,


struct sockaddr *from, socklen_t *fromlen);

int recvmsg(int s, struct msghdr *msg, int flags);

DESCRIPTION
The recvfrom and recvmsg calls are used to receive mes-
sages from a socket, and may be used to receive data on a
socket whether or not it is connection−oriented.

If from is not NULL, and the socket is not connection−ori-


ented, the source address of the message is filled in.
The argument fromlen is a value−result parameter, initial-
ized to the size of the buffer associated with from, and
modified on return to indicate the actual size of the
address stored there.

The recv call is normally used only on a connected socket


(see connect(2)) and is identical to recvfrom with a NULL
from parameter.

All three routines return the length of the message on


successful completion. If a message is too long to fit in
the supplied buffer, excess bytes may be discarded depend-
ing on the type of socket the message is received from
(see socket(2)).

If no messages are available at the socket, the receive


calls wait for a message to arrive, unless the socket is
nonblocking (see fcntl(2)) in which case the value −1 is
returned and the external variable errno set to EAGAIN.
The receive calls normally return any data available, up
to the requested amount, rather than waiting for receipt
of the full amount requested.

The select(2) or poll(2) call may be used to determine


when more data arrives.

The flags argument to a recv call is formed by OR’ing one


or more of the following values:

MSG_OOB
This flag requests receipt of out−of−band data that
would not be received in the normal data stream.
Some protocols place expedited data at the head of

Linux Man Page Apr 1999 1


RECV(2) Linux Programmer’s Manual RECV(2)

the normal data queue, and thus this flag cannot be


used with such protocols.

MSG_PEEK
This flag causes the receive operation to return
data from the beginning of the receive queue with-
out removing that data from the queue. Thus, a
subsequent receive call will return the same data.

MSG_WAITALL
This flag requests that the operation block until
the full request is satisfied. However, the call
may still return less data than requested if a sig-
nal is caught, an error or disconnect occurs, or
the next data to be received is of a different type
than that returned.

MSG_NOSIGNAL
This flag turns off raising of SIGPIPE on stream
sockets when the other end disappears.

MSG_ERRQUEUE
This flag specifies that queued errors should be
received from the socket error queue. The error is
passed in an ancillary message with a type depen-
dent on the protocol (for IPv4 IP_RECVERR ). The
user should supply a buffer of sufficient size.
See cmsg(3) for more information on ancillary mes-
sages.

The error is supplied in a sock_extended_err struc-


ture:

#define SO_EE_ORIGIN_NONE 0
#define SO_EE_ORIGIN_LOCAL 1
#define SO_EE_ORIGIN_ICMP 2
#define SO_EE_ORIGIN_ICMP6 3

struct sock_extended_err
{
u_int32_t ee_errno; /* error number */
u_int8_t ee_origin; /* where the error originated
*/
u_int8_t ee_type; /* type */
u_int8_t ee_code; /* code */
u_int8_t ee_pad;
u_int32_t ee_info; /* additional information */
u_int32_t ee_data; /* other data */
/* More data may follow */
};

struct sockaddr *SOCK_EE_OFFENDER(struct sock_extended_err *)


;

ee_errno contains the errno number of the queued


error. ee_origin is the origin code of where the

Linux Man Page Apr 1999 2


RECV(2) Linux Programmer’s Manual RECV(2)

error originated. The other fields are protocol


specific. The macro SOCK_EE_OFFENDER returns a
pointer to the address of the network object where
the error originated from given a pointer to the
ancillary message. If this address is not known,
the sa_family member of the sockaddr contains
AF_UNSPEC and the other fields of the sockaddr are
undefined. The payload of the packet that caused
the error is passed as normal data.

For local errors, no address is passed (this can be


checked with the cmsg_len member of the cmsghdr).
For error receives, the MSG_ERRQUEUE is set in the
msghdr. After an error has been passed, the pend-
ing socket error is regenerated based on the next
queued error and will be passed on the next socket
operation.

The recvmsg call uses a msghdr structure to minimize the


number of directly supplied parameters. This structure
has the following form, as defined in <sys/socket.h>:

struct msghdr {
void * msg_name; /* optional address */
socklen_t msg_namelen; /* size of address */
struct iovec * msg_iov; /* scatter/gather array */
size_t msg_iovlen; /* # elements in msg_iov */
void * msg_control; /* ancillary data, see below
*/
socklen_t msg_controllen; /* ancillary data buffer len
*/
int msg_flags; /* flags on received message
*/
};

Here msg_name and msg_namelen specify the destination


address if the socket is unconnected; msg_name may be
given as a null pointer if no names are desired or
required. The fields msg_iov and msg_iovlen describe
scatter−gather locations, as discussed in readv(2). The
field msg_control, which has length msg_controllen, points
to a buffer for other protocol control related messages or
miscellaneous ancillary data. When recvmsg is called,
msg_controllen should contain the length of the available
buffer in msg_control; upon return from a successful call
it will contain the length of the control message
sequence.

The messages are of the form:

struct cmsghdr {
socklen_t cmsg_len; /* data byte count, including hdr
*/
int cmsg_level; /* originating protocol */
int cmsg_type; /* protocol−specific type */
/* followed by
u_char cmsg_data[]; */
};
Linux Man Page Apr 1999 3

RECV(2) Linux Programmer’s Manual RECV(2)

Ancillary data should only be accessed by the macros


defined in cmsg(3).

As an example, Linux uses this auxiliary data mechanism to


pass extended errors, IP options or file descriptors over
Unix sockets.

The msg_flags field is set on return according to the mes-


sage received. MSG_EOR indicates end−of−record; the data
returned completed a record (generally used with sockets
of type SOCK_SEQPACKET). MSG_TRUNC indicates that the
trailing portion of a datagram was discarded because the
datagram was larger than the buffer supplied. MSG_CTRUNC
indicates that some control data were discarded due to
lack of space in the buffer for ancillary data. MSG_OOB
is returned to indicate that expedited or out−of−band data
were received. MSG_ERRQUEUE indicates that no data was
received but an extended error from the socket error
queue.

RETURN VALUES
These calls return the number of bytes received, or −1 if
an error occurred.

ERRORS
These are some standard errors generated by the socket
layer. Additional errors may be generated and returned
from the underlying protocol modules; see their manual
pages.

EBADF The argument s is an invalid descriptor.

ECONNREFUSED
A remote host refused to allow the network connec-
tion (typically because it is not running the
requested service).

ENOTCONN
The socket is associated with a connection−oriented
protocol and has not been connected (see connect(2)
and accept(2)).

ENOTSOCK
The argument s does not refer to a socket.

EAGAIN The socket is marked non−blocking and the receive


operation would block, or a receive timeout had
been set and the timeout expired before data was
received.

EINTR The receive was interrupted by delivery of a signal


before any data were available.

EFAULT The receive buffer pointer(s) point outside the


Linux Man Page Apr 1999 4

RECV(2) Linux Programmer’s Manual RECV(2)

process’s address space.

EINVAL Invalid argument passed.

CONFORMING TO
4.4BSD (these function calls first appeared in 4.2BSD).

NOTE
The prototypes given above follow glibc2. The Single Unix
Specification agrees, except that it has return values of
type ‘ssize_t’ (while BSD 4.* and libc4 and libc5 all have
‘int’). The flags argument is ‘int’ in BSD 4.*, but
‘unsigned int’ in libc4 and libc5. The len argument is
‘int’ in BSD 4.*, but ‘size_t’ in libc4 and libc5. The
fromlen argument is ‘int *’ in BSD 4.*, libc4 and libc5.
The present ‘socklen_t *’ was invented by POSIX. See
also accept(2).

SEE ALSO
fcntl(2), read(2), select(2), getsockopt(2), socket(2),
cmsg(3)
Linux Man Page Apr 1999 5

SEND(2) Linux Programmer’s Manual SEND(2)

NAME
send, sendto, sendmsg − send a message from a socket

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

int send(int s, const void *msg, size_t len, int flags);


int sendto(int s, const void *msg, size_t len, int flags,
const struct sockaddr *to, socklen_t tolen);
int sendmsg(int s, const struct msghdr *msg, int flags);

DESCRIPTION
Send, sendto, and sendmsg are used to transmit a message
to another socket. Send may be used only when the socket
is in a connected state, while sendto and sendmsg may be
used at any time.

The address of the target is given by to with tolen speci-


fying its size. The length of the message is given by
len. If the message is too long to pass atomically
through the underlying protocol, the error EMSGSIZE is
returned, and the message is not transmitted.

No indication of failure to deliver is implicit in a send.


Locally detected errors are indicated by a return value of
−1.

When the message does not fit into the send buffer of the
socket, send normally blocks, unless the socket has been
placed in non−blocking I/O mode. In non−blocking mode it
would return EAGAIN in this case. The select(2) call may
be used to determine when it is possible to send more
data.

The flags parameter is a flagword and can contain the fol-


lowing flags:

MSG_OOB
Sends out−of−band data on sockets that support this
notion (e.g. SOCK_STREAM); the underlying protocol
must also support out−of−band data.

MSG_DONTROUTE
Dont’t use a gateway to send out the packet, only
send to hosts on directly connected networks. This
is usually used only by diagnostic or routing pro-
grams. This is only defined for protocol families
that route; packet sockets don’t.

MSG_DONTWAIT
Enables non−blocking operation; if the operation
would block, EAGAIN is returned (this can also be
enabled using the O_NONBLOCK with the F_SETFL
Linux Man Page July 1999 1

SEND(2) Linux Programmer’s Manual SEND(2)

fcntl(2)).

MSG_NOSIGNAL
Requests not to send SIGPIPE on errors on stream
oriented sockets when the other end breaks the con-
nection. The EPIPE error is still returned.

See recv(2) for a description of the msghdr structure. You


may send control information using the msg_control and
msg_controllen members. The maximum control buffer length
the kernel can process is limited per socket by the
net.core.optmem_max sysctl; see socket(7).

RETURN VALUES
The calls return the number of characters sent, or −1 if
an error occurred.

ERRORS
These are some standard errors generated by the socket
layer. Additional errors may be generated and returned
from the underlying protocol modules; see their respective
manual pages.

EBADF An invalid descriptor was specified.

ENOTSOCK
The argument s is not a socket.

EFAULT An invalid user space address was specified for a


parameter.

EMSGSIZE
The socket requires that message be sent atomi-
cally, and the size of the message to be sent made
this impossible.

EAGAIN or EWOULDBLOCK
The socket is marked non−blocking and the requested
operation would block.

ENOBUFS
The output queue for a network interface was full.
This generally indicates that the interface has
stopped sending, but may be caused by transient
congestion. (This cannot occur in Linux, packets
are just silently dropped when a device queue over-
flows.)

EINTR A signal occurred.

ENOMEM No memory available.

EINVAL Invalid argument passed.


Linux Man Page July 1999 2

SEND(2) Linux Programmer’s Manual SEND(2)

EPIPE The local end has been shut down on a connection


oriented socket. In this case the process will
also receive a SIGPIPE unless MSG_NOSIGNAL is set.

CONFORMING TO
4.4BSD, SVr4, POSIX 1003.1g draft (these function calls
appeared in 4.2BSD).

NOTE
The prototypes given above follow the Single Unix Specifi-
cation, as glibc2 also does; the flags argument was ‘int’
in BSD 4.*, but ‘unsigned int’ in libc4 and libc5; the len
argument was ‘int’ in BSD 4.* and libc4, but ‘size_t’ in
libc5; the tolen argument was ‘int’ in BSD 4.* and libc4
and libc5. See also accept(2).

SEE ALSO
fcntl(2), recv(2), select(2), getsockopt(2), sendfile(2),
socket(2), write(2), socket(7), ip(7), tcp(7), udp(7)
Linux Man Page July 1999 3

You might also like