recv

Top  Previous  Next

The recv function receives data from a connected socket or a bound connectionless socket.  It is usually used with connected sockets because it does not permit the application to retrieve the source address of the received data.

The function blocks until any data is available, connection is closed by peer or if an error occurs.

 

For message-based sockets (SOCK_DGRAM), the entire message has to be 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.

For stream-based sockets (SOCK_STREAM), message boundaries are ignored, data is returned to the user as soon as it becomes available and no data is discarded.

 

Syntax

ssize_t recv(

int socket,

void *buf,

size_t len,

int flags

);

 

Parameters

socket

The descriptor that identifies a socket.

 

buf

A pointer to the buffer to receive the incoming data.

 

len

The length, in bytes, of the buffer pointed to by the buf parameter.

 

flags

Specifies the type of message reception. Values of this argument are formed by logically OR'ing zero or more of the  values in the following table.

 

Type

Meaning

MSG_PEEK

Peeks at an incoming message. The data is treated as unread and next recv or similar function shall still return this data.

MSG_OOB

Requests out-of-band data. The significance and semantics of out-of-band data are protocol-specific.

MSG_WAITALL

On SOCK_STREAM sockets this requests that the function block until the full amount of data can be returned. This function may return the smaller amount of data if the socket is a message-based socket, if the connection is terminated, if MSG_PEEK was specified, or if an error is pending for the socket.

 

Return value

Upon successful completion, recv returns the length of the message in bytes. If no messages are available to be received and the peer has performed an orderly shutdown, recv returns 0. Otherwise, -1 is returned and errno set to indicate the error.