recv

Reads data from a socket and stores it in a buffer.

Library:LibC
Standard:BSD
Service:Networking

Syntax

  #include <sys/socket.h> 
   
  ssize_t recv (
     int       s,
     void     *buf,
     size_t    len,
     int       flags);
  

Parameters

s

(IN) Specifies the socket file handle from which data is to be read.

buf

(OUT) Points to a buffer in which data is to be stored.

len

(IN) Specifies the length of the buffer specified in buf.

flags

(IN) Specifies the type of message reception. See Message Types.

Return Values

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 to one of the following:

Decimal

Constant

Description

4

EBADF

The socket parameter is an invalid socket file handle.

9

EINVAL

MSG_OOB is invalid when used with SO_OOBINLINE, or the out-of-band data is not present.

35

EWOULDBLOCK

The socket is marked nonblocking, and the receive operation would block.

38

ENOTSOCK

The socket parameter does not reference a socket handle.

45

EOPNOTSUPP

The specified flags are not supported.

57

ENOTCONN

The socket is not in a connected state.

Remarks

The recv function is normally used with connected sockets because the application cannot 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 recv function blocks.

  • If the socket is nonblocking because the O_NONBLOCK flag is set on the socket handle, recv returns -1 and sets errno to EWOULDBLOCK.

Call select to determine when more data arrives.

The MSG_OOB flag 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.

The MSG_PEEK flag permits the socket client to look at a message or STREAM data without removing it from the socket.

See Also