Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

610 Network IPC: Sockets Chapter 16


16.5 DataTr ansfer


Since a socket endpoint is represented as a file descriptor,wecan usereadandwrite
to communicate with a socket, as long as it is connected. Recall that a datagram socket
can be ‘‘connected’’ if we set the default peer address using theconnectfunction.
Usingreadandwritewith socket descriptors is significant, because it means that we
can pass socket descriptors to functions that wereoriginally designed to work with local
files. Wecan also arrange to pass the socket descriptors to child processes that execute
programs that know nothing about sockets.
Although we can exchange data usingreadandwrite,that is about all we can do
with these two functions. If we want to specify options, receive packets from multiple
clients, or send out-of-band data, we need to use one of the six socket functions
designed for data transfer.
Three functions areavailable for sending data, and three areavailable for receiving
data. First, we’ll look at the ones used to send data.
The simplest one issend.It is similar towrite,but allows us to specify flags to
change how the data we want to transmit is treated.

#include <sys/socket.h>

ssize_t send(intsockfd,const void *buf,size_tnbytes,intflags);

Returns: number of bytes sent if OK,−1 on error

Likewrite,the socket has to be connected to usesend.Thebufandnbytesarguments
have the same meaning as they do withwrite.
Unlikewrite,however,sendsupports a fourthflagsargument. Three flags are
defined by the Single UNIX Specification, but it is common for implementations to
support additional ones. They aresummarized in Figure16.13.
Ifsendreturns success, it doesn’t necessarily mean that the process at the other end
of the connection receives the data. All we areguaranteed is that whensendsucceeds,
the data has been delivered to the network drivers without error.
With a protocol that supports message boundaries, if we try to send a single
message larger than the maximum supported by the protocol,sendwill fail with
errnoset toEMSGSIZE.With a byte-stream protocol,sendwill block until the entire
amount of data has been transmitted.
Thesendtofunction is similar tosend.The difference is thatsendtoallows us to
specify a destination address to be used with connectionless sockets.

#include <sys/socket.h>

ssize_t sendto(intsockfd,const void *buf,size_tnbytes,intflags,
const struct sockaddr *destaddr,socklen_t destlen);

Returns: number of bytes sent if OK,−1 on error

With a connection-oriented socket, the destination address is ignored, as the destination
is implied by the connection. With a connectionless socket, we can’t usesendunless
Free download pdf