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

NAME

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

SYNOPSIS

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

DESCRIPTION

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

RETURN VALUE

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

ERRORS

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

CONFORMING TO

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

NOTES

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

EXAMPLES

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

SEE ALSO

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

COLOPHON

326       This  page  is  part of release 5.12 of the Linux man-pages project.  A
327       description of the project, information about reporting bugs,  and  the
328       latest     version     of     this    page,    can    be    found    at
329       https://www.kernel.org/doc/man-pages/.
330
331
332
333Linux                             2021-03-22                           RECV(2)
Impressum