1RECV(2)                    Linux Programmer's Manual                   RECV(2)


6       recv, recvfrom, recvmsg - receive a message from a socket


9       #include <sys/types.h>
10       #include <sys/socket.h>
12       ssize_t recv(int sockfd, void *buf, size_t len, int flags);
14       ssize_t recvfrom(int sockfd, void *buf, size_t len, int flags,
15                        struct sockaddr *src_addr, socklen_t *addrlen);
17       ssize_t recvmsg(int sockfd, struct msghdr *msg, int flags);


20       The  recv(),  recvfrom(),  and recvmsg() calls are used to receive mes‐
21       sages from a socket.  They may be used to receive data on both  connec‐
22       tionless  and  connection-oriented  sockets.  This page first describes
23       common features of all three system calls, and then describes the  dif‐
24       ferences between the calls.
26       The  only  difference  between  recv()  and  read(2) is the presence of
27       flags.  With a zero flags argument, recv() is generally  equivalent  to
28       read(2) (but see NOTES).  Also, the following call
30           recv(sockfd, buf, len, flags);
32       is equivalent to
34           recvfrom(sockfd, buf, len, flags, NULL, NULL);
36       All  three calls return the length of the message on successful comple‐
37       tion.  If a message is too long to fit in the supplied  buffer,  excess
38       bytes  may  be discarded depending on the type of socket the message is
39       received from.
41       If no messages are available at the socket, the receive calls wait  for
42       a  message  to arrive, unless the socket is nonblocking (see fcntl(2)),
43       in which case the value -1 is returned and the external variable  errno
44       is set to EAGAIN or EWOULDBLOCK.  The receive calls normally return any
45       data available, up to the requested amount, rather than waiting for re‐
46       ceipt of the full amount requested.
48       An  application  can  use  select(2), poll(2), or epoll(7) to determine
49       when more data arrives on a socket.
51   The flags argument
52       The flags argument is formed by ORing one or more of the following val‐
53       ues:
55       MSG_CMSG_CLOEXEC (recvmsg() only; since Linux 2.6.23)
56              Set  the close-on-exec flag for the file descriptor received via
57              a UNIX domain file descriptor  using  the  SCM_RIGHTS  operation
58              (described  in  unix(7)).  This flag is useful for the same rea‐
59              sons as the O_CLOEXEC flag of open(2).
61       MSG_DONTWAIT (since Linux 2.2)
62              Enables nonblocking operation; if the operation would block, the
63              call  fails with the error EAGAIN or EWOULDBLOCK.  This provides
64              similar behavior to setting the O_NONBLOCK  flag  (via  the  fc‐
65              ntl(2) F_SETFL operation), but differs in that MSG_DONTWAIT is a
66              per-call option, whereas O_NONBLOCK is a  setting  on  the  open
67              file description (see open(2)), which will affect all threads in
68              the calling process and as well as  other  processes  that  hold
69              file descriptors referring to the same open file description.
71       MSG_ERRQUEUE (since Linux 2.2)
72              This  flag  specifies that queued errors should be received from
73              the socket error queue.  The error is  passed  in  an  ancillary
74              message  with  a  type  dependent  on  the  protocol  (for  IPv4
75              IP_RECVERR).  The user should  supply  a  buffer  of  sufficient
76              size.   See cmsg(3) and ip(7) for more information.  The payload
77              of the original packet that caused the error is passed as normal
78              data  via  msg_iovec.   The  original destination address of the
79              datagram that caused the error is supplied via msg_name.
81              The error is supplied in a sock_extended_err structure:
83                  #define SO_EE_ORIGIN_NONE    0
84                  #define SO_EE_ORIGIN_LOCAL   1
85                  #define SO_EE_ORIGIN_ICMP    2
86                  #define SO_EE_ORIGIN_ICMP6   3
88                  struct sock_extended_err
89                  {
90                      uint32_t ee_errno;   /* Error number */
91                      uint8_t  ee_origin;  /* Where the error originated */
92                      uint8_t  ee_type;    /* Type */
93                      uint8_t  ee_code;    /* Code */
94                      uint8_t  ee_pad;     /* Padding */
95                      uint32_t ee_info;    /* Additional information */
96                      uint32_t ee_data;    /* Other data */
97                      /* More data may follow */
98                  };
100                  struct sockaddr *SO_EE_OFFENDER(struct sock_extended_err *);
102              ee_errno contains the errno number of the queued error.  ee_ori‐
103              gin is the origin code of where the error originated.  The other
104              fields are protocol-specific.  The  macro  SOCK_EE_OFFENDER  re‐
105              turns  a  pointer to the address of the network object where the
106              error originated from given a pointer to the ancillary  message.
107              If  this address is not known, the sa_family member of the sock‐
108              addr contains AF_UNSPEC and the other fields of the sockaddr are
109              undefined.   The  payload of the packet that caused the error is
110              passed as normal data.
112              For local errors, no address is passed (this can be checked with
113              the  cmsg_len  member  of the cmsghdr).  For error receives, the
114              MSG_ERRQUEUE flag is set in the msghdr.  After an error has been
115              passed,  the  pending  socket  error is regenerated based on the
116              next queued error and will be passed on the next  socket  opera‐
117              tion.
119       MSG_OOB
120              This flag requests receipt of out-of-band data that would not be
121              received in the normal data stream.  Some protocols place  expe‐
122              dited  data  at the head of the normal data queue, and thus this
123              flag cannot be used with such protocols.
125       MSG_PEEK
126              This flag causes the receive operation to return data  from  the
127              beginning  of  the receive queue without removing that data from
128              the queue.  Thus, a subsequent receive call will return the same
129              data.
131       MSG_TRUNC (since Linux 2.2)
132              For    raw   (AF_PACKET),   Internet   datagram   (since   Linux
133              2.4.27/2.6.8), netlink (since Linux 2.6.22), and  UNIX  datagram
134              (since  Linux 3.4) sockets: return the real length of the packet
135              or datagram, even when it was longer than the passed buffer.
137              For use with Internet stream sockets, see tcp(7).
139       MSG_WAITALL (since Linux 2.2)
140              This flag requests that the operation block until the  full  re‐
141              quest  is  satisfied.   However,  the call may still return less
142              data than requested if a signal is caught, an error  or  discon‐
143              nect  occurs,  or the next data to be received is of a different
144              type than that returned.  This flag has no effect  for  datagram
145              sockets.
147   recvfrom()
148       recvfrom() places the received message into the buffer buf.  The caller
149       must specify the size of the buffer in len.
151       If src_addr is not NULL,  and  the  underlying  protocol  provides  the
152       source  address  of  the  message, that source address is placed in the
153       buffer pointed to by src_addr.  In this case, addrlen is a value-result
154       argument.  Before the call, it should be initialized to the size of the
155       buffer associated with src_addr.  Upon return, addrlen  is  updated  to
156       contain the actual size of the source address.  The returned address is
157       truncated if the buffer provided is too small; in  this  case,  addrlen
158       will return a value greater than was supplied to the call.
160       If the caller is not interested in the source address, src_addr and ad‐
161       drlen should be specified as NULL.
163   recv()
164       The recv() call is normally used only on a connected socket  (see  con‐
165       nect(2)).  It is equivalent to the call:
167           recvfrom(fd, buf, len, flags, NULL, 0);
169   recvmsg()
170       The  recvmsg()  call  uses a msghdr structure to minimize the number of
171       directly supplied arguments.  This structure is defined as  follows  in
172       <sys/socket.h>:
174           struct iovec {                    /* Scatter/gather array items */
175               void  *iov_base;              /* Starting address */
176               size_t iov_len;               /* Number of bytes to transfer */
177           };
179           struct msghdr {
180               void         *msg_name;       /* Optional address */
181               socklen_t     msg_namelen;    /* Size of address */
182               struct iovec *msg_iov;        /* Scatter/gather array */
183               size_t        msg_iovlen;     /* # elements in msg_iov */
184               void         *msg_control;    /* Ancillary data, see below */
185               size_t        msg_controllen; /* Ancillary data buffer len */
186               int           msg_flags;      /* Flags on received message */
187           };
189       The  msg_name field points to a caller-allocated buffer that is used to
190       return the source address if the socket  is  unconnected.   The  caller
191       should  set  msg_namelen  to  the size of this buffer before this call;
192       upon return from a successful call, msg_namelen will contain the length
193       of  the returned address.  If the application does not need to know the
194       source address, msg_name can be specified as NULL.
196       The fields msg_iov and msg_iovlen describe scatter-gather locations, as
197       discussed in readv(2).
199       The  field  msg_control,  which  has length msg_controllen, points to a
200       buffer for other protocol control-related messages or miscellaneous an‐
201       cillary  data.  When recvmsg() is called, msg_controllen should contain
202       the length of the available buffer in msg_control; upon return  from  a
203       successful  call  it will contain the length of the control message se‐
204       quence.
206       The messages are of the form:
208           struct cmsghdr {
209               size_t cmsg_len;    /* Data byte count, including header
210                                      (type is socklen_t in POSIX) */
211               int    cmsg_level;  /* Originating protocol */
212               int    cmsg_type;   /* Protocol-specific type */
213           /* followed by
214               unsigned char cmsg_data[]; */
215           };
217       Ancillary data should  be  accessed  only  by  the  macros  defined  in
218       cmsg(3).
220       As  an  example,  Linux  uses this ancillary data mechanism to pass ex‐
221       tended errors, IP options, or file descriptors over UNIX  domain  sock‐
222       ets.   For  further information on the use of ancillary data in various
223       socket domains, see unix(7) and ip(7).
225       The msg_flags field in the msghdr is set on return  of  recvmsg().   It
226       can contain several flags:
228       MSG_EOR
229              indicates  end-of-record;  the  data returned completed a record
230              (generally used with sockets of type SOCK_SEQPACKET).
232       MSG_TRUNC
233              indicates that the trailing portion of a datagram was  discarded
234              because the datagram was larger than the buffer supplied.
236       MSG_CTRUNC
237              indicates  that  some  control data was discarded due to lack of
238              space in the buffer for ancillary data.
240       MSG_OOB
241              is returned to indicate that expedited or out-of-band  data  was
242              received.
244       MSG_ERRQUEUE
245              indicates  that  no data was received but an extended error from
246              the socket error queue.


249       These calls return the number of bytes received, or -1 if an error  oc‐
250       curred.  In the event of an error, errno is set to indicate the error.
252       When a stream socket peer has performed an orderly shutdown, the return
253       value will be 0 (the traditional "end-of-file" return).
255       Datagram sockets in various domains (e.g., the UNIX  and  Internet  do‐
256       mains) permit zero-length datagrams.  When such a datagram is received,
257       the return value is 0.
259       The value 0 may also be returned if the requested number  of  bytes  to
260       receive from a stream socket was 0.


263       These  are  some  standard errors generated by the socket layer.  Addi‐
264       tional errors may be generated and returned from the underlying  proto‐
265       col modules; see their manual pages.
268              The socket is marked nonblocking and the receive operation would
269              block, or a receive timeout had been set and the timeout expired
270              before data was received.  POSIX.1 allows either error to be re‐
271              turned for this case, and does not require  these  constants  to
272              have  the same value, so a portable application should check for
273              both possibilities.
275       EBADF  The argument sockfd is an invalid file descriptor.
278              A remote host refused to allow the network connection (typically
279              because it is not running the requested service).
281       EFAULT The  receive  buffer  pointer(s) point outside the process's ad‐
282              dress space.
284       EINTR  The receive was interrupted by delivery of a signal  before  any
285              data was available; see signal(7).
287       EINVAL Invalid argument passed.
289       ENOMEM Could not allocate memory for recvmsg().
291       ENOTCONN
292              The socket is associated with a connection-oriented protocol and
293              has not been connected (see connect(2) and accept(2)).
295       ENOTSOCK
296              The file descriptor sockfd does not refer to a socket.


299       POSIX.1-2001, POSIX.1-2008, 4.4BSD (these interfaces first appeared  in
300       4.2BSD).
302       POSIX.1 describes only the MSG_OOB, MSG_PEEK, and MSG_WAITALL flags.


305       If  a  zero-length datagram is pending, read(2) and recv() with a flags
306       argument of zero provide different  behavior.   In  this  circumstance,
307       read(2) has no effect (the datagram remains pending), while recv() con‐
308       sumes the pending datagram.
310       The socklen_t type was invented by POSIX.  See also accept(2).
312       According to POSIX.1, the msg_controllen field of the msghdr  structure
313       should  be typed as socklen_t, and the msg_iovlen field should be typed
314       as int, but glibc currently types both as size_t.
316       See recvmmsg(2) for information about a Linux-specific system call that
317       can be used to receive multiple datagrams in a single call.


320       An example of the use of recvfrom() is shown in getaddrinfo(3).


323       fcntl(2),  getsockopt(2), read(2), recvmmsg(2), select(2), shutdown(2),
324       socket(2), cmsg(3), sockatmark(3), ip(7), ipv6(7),  socket(7),  tcp(7),
325       udp(7), unix(7)


328       This  page  is  part of release 5.10 of the Linux man-pages project.  A
329       description of the project, information about reporting bugs,  and  the
330       latest     version     of     this    page,    can    be    found    at
331       https://www.kernel.org/doc/man-pages/.
335Linux                             2020-11-01                           RECV(2)