1recv(2)                       System Calls Manual                      recv(2)
2
3
4

NAME

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

LIBRARY

9       Standard C library (libc, -lc)
10

SYNOPSIS

12       #include <sys/socket.h>
13
14       ssize_t recv(int sockfd, void buf[.len], size_t len,
15                        int flags);
16       ssize_t recvfrom(int sockfd, void buf[restrict .len], size_t len,
17                        int flags,
18                        struct sockaddr *_Nullable restrict src_addr,
19                        socklen_t *_Nullable restrict addrlen);
20       ssize_t recvmsg(int sockfd, struct msghdr *msg, int flags);
21

DESCRIPTION

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

RETURN VALUE

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

ERRORS

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

VERSIONS

302       According to POSIX.1, the msg_controllen field of the msghdr  structure
303       should  be typed as socklen_t, and the msg_iovlen field should be typed
304       as int, but glibc currently types both as size_t.
305

STANDARDS

307       POSIX.1-2008.
308

HISTORY

310       POSIX.1-2001, 4.4BSD (first appeared in 4.2BSD).
311
312       POSIX.1 describes only the MSG_OOB, MSG_PEEK, and MSG_WAITALL flags.
313

NOTES

315       If a zero-length datagram is pending, read(2) and recv() with  a  flags
316       argument  of  zero  provide  different behavior.  In this circumstance,
317       read(2) has no effect (the datagram remains pending), while recv() con‐
318       sumes the pending datagram.
319
320       See recvmmsg(2) for information about a Linux-specific system call that
321       can be used to receive multiple datagrams in a single call.
322

EXAMPLES

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

SEE ALSO

327       fcntl(2), getsockopt(2), read(2), recvmmsg(2), select(2),  shutdown(2),
328       socket(2),  cmsg(3),  sockatmark(3), ip(7), ipv6(7), socket(7), tcp(7),
329       udp(7), unix(7)
330
331
332
333Linux man-pages 6.05              2023-07-18                           recv(2)
Impressum