Reads data from a socket, stores it in a buffer, and obtains source address information.
#include <sys/socket.h>
ssize_t recvfrom (
int s,
void *buf,
size_t len,
int flags,
struct sockaddr *from,
size_t *fromlen);
(IN) Specifies the socket file handle from which data is to be read.
(OUT) Points to a buffer in which data is to be stored.
(IN) Specifies the length of the buffer specified in buf.
(IN) Specifies the type of message reception. See Message Types.
(OUT) Points to the location of the structure containing the source address of the message. For IPv4, addr points to a sockaddr structure; for IPv6, to a sockaddr_in6 structure. The first two bytes in the structures identify the protocol family, and hence the structure.
(IN/OUT) Points to the length of the buffer associated with from.
If successful, returns the number of bytes received. If no message is available and the peer has performed an orderly shutdown, returns 0. Otherwise, returns -1 and sets errno one of the following:
The recvfrom function is normally used with connectionless sockets because the application can retrieve the source address of the received data.
From a message-based socket, such as a SOCK_DGRAM socket, the entire message is read in a single operation. If a message is too long to fit in the supplied buffer, and MSG_PEEK is not set in the flags argument, the excess bytes are discarded.
From a stream-based socket, such as a SOCK_STREAM socket, data is returned to a user as soon as it is available and no data is discarded.
If data is not available at the socket, one of the following occurs:
If the O_NONBLOCK flag is not set on the socket handle, the recvfrom function blocks.
If the socket is nonblocking because the O_NONBLOCK flag is set on the socket handle, recvfrom returns -1 and sets errno to EWOULDBLOCK.
MSG_OOB is used only with TCP sockets. MSG_OOB actually refers to the byte of data following a TCP urgent boundary. After the socket client has discovered new out-of-band data (by calling select for exceptions) and has read normal data up to the out-of-band byte, it reads one byte of out-of-band data by setting the MSG_OOB flag.
MSG_PEEK permits the socket client to look at a message or STREAM data without removing it from the socket.
If from is nonzero, the source address of the message is filled.
For a UDP socket, if a message is too long to fit in the supplied buffer, recvfrom truncates the excess bytes.