Interview Questions

Code Sample:Data Transfer over Connected Sockets - send() and recv()

Beginners Guide to Sockets


(Continued from previous question...)

Code Sample:Data Transfer over Connected Sockets - send() and recv()

Two additional data transfer library calls, namely send() and recv(), are available if the sockets are connected. They correspond very closely to the read() and write() functions used for I/O on ordinary file descriptors.

#include &ltsys/types.h>
#include &ltsys/socket.h>

int send(int sd, char *buf, int len, int flags)

int recv(int sd, char * buf, int len, int flags)

In both cases, sd is the socket descriptor. For send(), buf points to a buffer containing the data to be sent, len is the length of the data and flags will usually be 0. The return value is the number of bytes sent if successful. If not successful, -1 is returned and errno describes the error.

For recv(), buf points to a data area into which the received data is copied, len is the size of this data area in bytes, and flags is usually either 0 or set to MSG_PEEK if the received data is to be retained in the system after it is received. The return value is the number of bytes received if successful. If not successful, -1 is returned and errno describes the error.

(Continued on next question...)

Other Interview Questions