recv
Prototype:
#include <sys/socket.h>
#include <resolv.h>
int recv(int sockfd, char* buf, int maxbuf,
    int options);
General Description: Wait for and accept a message from a connected peer, client, or server. The system call behaves similarly to read() but adds control flags. UDP may use this call if connected to peer.
Return Value: The number of bytes read or -1 if an error occurred.
Parameters
sockfd The open socket descriptor.
buf The byte array to accept the incoming-message.
maxbuf The size of the array.
options A set of flags that can be arithmetically or'ed together.
  • MSG_OOB - This flag requests receipt of out-of-band data that would not be received in the normal data stream. Some protocols place expedited data at the head of the normal data queue, and thus this flag cannot be used with such protocols.
  • MSG_PEEK - This flag causes the receive operation to return data from the beginning of the receive queue without removing that data from the queue. Thus, a subsequent receive call will return the same data.
  • MSG_WAITALL - This flag requests that the operation block until the full request is satisfied. However, the call may still return less data than requested if a signal is caught, an error or disconnect occurs, or the next data to be received is of a different type than that returned.
  • MSG_ERRQUEUE - Receive packet from the error queue.
  • MSG_NOSIGNAL - This flag turns off raising of SIGPIPE on stream sockets when the other end disappears.
  • MSG_ERRQUEUE - This flag specifies that queued errors should be received from the socket error queue. The error is passed in an ancillary message with a type dependent on the protocol (for IP, IP_RECVERR).
The error is supplied in a sock_extended_error structure
Possible Errors
EBADF The argument s is an invalid descriptor.
ENOTCONN The socket is associated with a connection-oriented protocol and has not been connected (see connect() and accept()).
ENOTSOCK The argument sockfd does not refer to a socket.
EAGAIN The socket is marked non-blocking and the receive-operation would block, or a receive-timeout had been set and the timeout expired before data was received.
EINTR A signal interrupted the receive-operation before any data was available.
EFAULT The receive buffer pointer point outside the process's address space.
EINVAL Invalid argument passed.
Examples
int sockfd;
int bytes, bytes_wrote=0;
/*--- Create socket, connect to server/peer ---*/
if ( (bytes = recv(sockfd, buffer, msg_len, 0)) < 0 )
    perror("send");
int sockfd;
int bytes, bytes_wrote=0;
/*--- Create socket, connect to server ---*/
if ( (bytes = recv(sockfd, buffer, msg_len, MSG_OOB)) < 0 )
    perror("Urgent message");