recv

recv receives data on a socket and returns the number of bytes received. recv may be used only on a connected socket. The number of bytes returned might be smaller than a provided buffer. On a stream protocol recv returns a portion of the received data stream, which fits in a provided buffer. On a non-stream socket, if the data is too long to fit in the supplied buffer, excess bytes are discarded.

On a blocking socket recv would block until some data has been received. On a non-blocking socket, in absence of received data, recv would fail with EWOULDBLOCK error code.

Syntax

int recv(
    SOCKET s,
    char *buf,
    int len,
    int flags
);

Parameters

s

The descriptor that identifies a connected socket.

buf

An integer that defines the size in bytes of buf.

flags

Receive flags. The logical OR of one or more of the following:

Flag Description

MSG_PEEK

This value can be used to read the data while it is still maintaining its position in the queue as originally received. The next recv call will read the same data.

MSG_OOB

This value can be used to receive out-of-band data. If no out-of-band data is present, recv will return -1. Urgent data is data that was sent with the MSG_OOB flag. The application is responsible for any special handling that may be required for the delivery of urgent data. Urgent data is only implemented for TCP.

Note: For TCP, if the MSG_OOB flag is specified and either no urgent data is present or the socket option SO_OOBINLINE has been specified, recv returns -1. If there is urgent data on its way but it has not yet arrived, recv returns -1 and WSAGetLastError returns WSAEWOULDBLOCK.

Presence of out-of band data can be checked by select function with a socket descriptor in the exception dataset.

Return Value

A positive value if the function succeeds, -1 if the function fails

Use WSAGetLastError to retrieve a specific error code.

Remarks

For a TCP socket, a return value of zero indicates that the peer TCP has sent a FIN packet and that no more data will be received from the socket. Unless the application has more data to send to the peer, the usual response to the return of zero is to close the socket. Note, however, that via the shutdown function, a peer can close only its send direction, causing zero to be returned from recv and the application can continue to transmit data to the peer and the peer can continue to read the data. Whether this is appropriate behavior is strictly an application-layer issue.

For a non-stream socket a return value of zero indicates that a zero-length message was received.

Requirements

Minimum Supported Version RTX64 2013
Header Winsock2.h
Library RtTcpip.lib