read()

The read() call reads data on a socket with descriptor s and stores it in a buffer. The read() call applies only to connected sockets. This call returns as many as len bytes of data. If fewer than the number of bytes requested is available, the call returns the number currently available. If data is not available for the socket s, and s is in blocking mode, the read() call blocks the caller until data arrives. If data is not available, and s is in nonblocking mode, read() returns a -1 and sets errno to EWOULDBLOCK. See ioctl(), or fcntl() for a description of how to set nonblocking mode.

If a datagram packet is too long to fit in the supplied buffer, datagram sockets discard extra bytes. Stream sockets act like streams of information with no boundaries separating data. For example, if applications A and B are connected with a stream socket and Application A sends 1000 bytes, each call to this function can return 1 byte, or 10 bytes, or the entire 1000 bytes. Therefore, applications using stream sockets should place this call in a loop, calling this function until all data has been received.

#include <manifest.h>
#include <socket.h>
int read(int s, char *buf, int len)
Parameter
Description
s
Socket descriptor.
buf
Points to the buffer that receives the data.
len
Length in bytes of the buffer pointed to by buf.

Return values

If successful, the number of bytes copied into the buffer is returned. The value 0 indicates that the connection is closed. The value -1 indicates an error. Errno identifies the specific error.
Errno
Description
EBADF
Indicates that s is not a valid socket descriptor.
EFAULT
Using the buf and len parameters would result in an attempt to access storage outside the caller address space.
EWOULDBLOCK
Indicates an unconnected socket (RAW).
Note: ENOTCONN is returned for TCP, and EINVAL is returned for UDP.
EMSGSIZE
For non-TCP sockets, this indicates that the length exceeds the maximum data size. This is determined by getsockopt() using SO_SNDBUF for the socket type (TCP, UDP, or RAW).

Related calls

connect(), fcntl(), getsockopt(), ioctl(), readv(), recv(), recvmsg(), recvfrom(), select(), selectex(), send(), sendmsg(), sendto(), setsockopt(), socket(), write(), writev()