The Linux Programming Interface

(nextflipdebug5) #1
Sockets: Advanced Topics 1259

61.3 Socket-Specific I/O System Calls: recv() and send()


The recv() and send() system calls perform I/O on connected sockets. They provide
socket-specific functionality that is not available with the traditional read() and
write() system calls.

The return value and the first three arguments to recv() and send() are the same as
for read() and write(). The last argument, flags, is a bit mask that modifies the
behavior of the I/O operation. For recv(), the bits that may be ORed in flags
include the following:
MSG_DONTWAIT
Perform a nonblocking recv(). If no data is available, then instead of block-
ing, return immediately with the error EAGAIN. We can obtain the same
behavior by using fcntl() to set nonblocking mode (O_NONBLOCK) on the socket,
with the difference that MSG_DONTWAIT allows us to control nonblocking
behavior on a per-call basis.
MSG_OOB
Receive out-of-band data on the socket. We briefly describe this feature in
Section 61.13.1.
MSG_PEEK
Retrieve a copy of the requested bytes from the socket buffer, but don’t
actually remove them from the buffer. The data can later be reread by
another recv() or read() call.
MSG_WAITALL
Normally, a recv() call returns the lesser of the number of bytes requested
(length) and the number of bytes actually available in the socket. Specifying
the MSG_WAITALL flag causes the system call to block until length bytes have
been received. However, even when this flag is specified, the call may
return fewer bytes than requested if: (a) a signal is caught; (b) the peer on a
stream socket terminated the connection; (c) an out-of-band data byte
(Section 61.13.1) was encountered; (d) the received message from a data-
gram socket is less than length bytes; or (e) an error occurs on the socket. (The
MSG_WAITALL flag can replace the readn() function that we show in Listing 61-1,
with the difference that our readn() function does restart itself if inter-
rupted by a signal handler.)

#include <sys/socket.h>

ssize_t recv(int sockfd, void *buffer, size_t length, int flags);
Returns number of bytes received, 0 on EOF, or –1 on error
ssize_t send(int sockfd, const void *buffer, size_t length, int flags);
Returns number of bytes sent, or –1 on error
Free download pdf