npc13
Post on 20-Dec-2014
195 Views
Preview:
DESCRIPTION
TRANSCRIPT
UNIX Network Programming 1
Chapter 13.
Advanced
I / O Functions
UNIX Network Programming 2
13.1 Introduction13.1 Introduction
• Socket Timeouts
• recv and send Functions
• readv and writev Functions
• recvmsg and sendmsg Function
• Ancillary Data
• How much Data is Queued?
• Sockets and Standard I/O
• T/TCP
UNIX Network Programming 3
13.2 Socket Timeouts13.2 Socket Timeouts
• Three ways to place a timeout on an I/O operation involving a socket
– Call alarm, which generates the SIGALRM signal when the specified time has expired.
– Block waiting for I/O in select, which has a time limit built in, instead of blocking in a call to read or write.
– Use the newer SO_RCVTIMEO and SO_SNDTIMEO socket options.
UNIX Network Programming 4
Connect with a Timeout Using SIGALRM (figure 13.1)Connect with a Timeout Using SIGALRM (figure 13.1)
#include "unp.h"
static voidconnect_alarm(int);
int connect_timeo(int sockfd, const SA *saptr, socklen_t salen, int nsec){
Sigfunc *sigfunc;int n;
sigfunc = Signal(SIGALRM, connect_alarm);if (alarm(nsec) != 0)
err_msg("connect_timeo: alarm was already set");
if ( (n = connect(sockfd, (struct sockaddr *) saptr, salen)) < 0) {close(sockfd);if (errno == EINTR)
errno = ETIMEDOUT;}alarm(0); /* turn off the alarm */Signal(SIGALRM, sigfunc); /* restore previous signal handler */
return(n);}
static voidconnect_alarm(int signo){
return; /* just interrupt the connect() */}
UNIX Network Programming 5
recvfrom with a Timeout Using SIGALRM (figure 13.2)recvfrom with a Timeout Using SIGALRM (figure 13.2)
#include "unp.h"
static void sig_alrm(int);
void dg_cli(FILE *fp, int sockfd, const SA *pservaddr, socklen_t servlen){
int n;char sendline[MAXLINE], recvline[MAXLINE + 1];
Signal(SIGALRM, sig_alrm);
while (Fgets(sendline, MAXLINE, fp) != NULL) {
Sendto(sockfd, sendline, strlen(sendline), 0, pservaddr, servlen);
alarm(5);if ( (n = recvfrom(sockfd, recvline, MAXLINE, 0, NULL, NULL)) < 0)
{if (errno == EINTR)
fprintf(stderr, "socket timeout\n");else
err_sys("recvfrom error");} else {
alarm(0);recvline[n] = 0; /* null terminate */Fputs(recvline, stdout);
}}
}
static void sig_alrm(int signo){
return; /* just interrupt the recvfrom() */}
UNIX Network Programming 6
recvfrom with a Timeout Using select (figure 13.3)recvfrom with a Timeout Using select (figure 13.3)
#include "unp.h"
int
readable_timeo(int fd, int sec)
{
fd_set rset;
struct timeval tv;
FD_ZERO(&rset);
FD_SET(fd, &rset);
tv.tv_sec = sec;
tv.tv_usec = 0;
return(select(fd+1, &rset, NULL, NULL, &tv));
/* 4> 0 if descriptor is readable */
}
UNIX Network Programming 7
recvfrom with a Timeout Using the SO_RCVTIMEO Socket recvfrom with a Timeout Using the SO_RCVTIMEO Socket Option (figure 13.5)Option (figure 13.5)voiddg_cli(FILE *fp, int sockfd, const SA *pservaddr, socklen_t servlen){
int n;char sendline[MAXLINE], recvline[MAXLINE + 1];struct timeval tv;
tv.tv_sec = 5;tv.tv_usec = 0;Setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
while (Fgets(sendline, MAXLINE, fp) != NULL) {
Sendto(sockfd, sendline, strlen(sendline), 0, pservaddr, servlen);
n = recvfrom(sockfd, recvline, MAXLINE, 0, NULL, NULL);if (n < 0) {
if (errno == EWOULDBLOCK) {fprintf(stderr, "socket timeout\n");continue;
} elseerr_sys("recvfrom error");
}recvline[n] = 0; /* null terminate */Fputs(recvline, stdout);
}}
UNIX Network Programming 8
13.3 recv and send Functions13.3 recv and send Functions
#include <sys/socket.h>
ssize_t recv (int sockfd, void *buff, size_t nbytes, int flags);
ssize_t send (int sockfd, const void *buff, size_t nbytes, int flags);
Flags Description recv send
MSG_DONTROUTEMSG_DONTWAITMSG_OOBMSG_PEEKMSG_WAITALL
bypass routing table lookuponly this operation is nonblockingsend or receive out-of-band datapeek at incoming messagewait for all the data
Figure 13.6 flags for I/O functions
UNIX Network Programming 9
13.4 readv and writev Functions13.4 readv and writev Functions
– readv and writev let us read into or write from one or more buffers with a single function call.
• are called scatter read and gather write.
#include <sys/uio.h>
ssize_t readv (int filedes, const struct iovec *iov, int iovcnt);
ssize_t writev (int filedes, const struct iovec *iov, int iovcnt);
Struct iovec {
void *iov_base; /* starting address of buffer */
size_t iov_len; /* size of buffer */
};
UNIX Network Programming 10
13.5 recvmsg and sendmsg Functions13.5 recvmsg and sendmsg Functions
#include <sys/socket.h>
ssize_t recvmsg (int sockfd, struct msghdr *msg, int flags);
ssize_t sendmsg (int sockfd, struct msghdr *msg, int flags);
Struct msghdr {
void *msg_name; /* starting address of buffer */
socklen_t msg_namelen; /* size of protocol address */
struct iovec *msg_iov; /* scatter/gather array */
size_t msg_iovlen; /* # elements in msg_iov */
void *msg_control; /* ancillary data; must be aligned
for a cmsghdr structure */
socklen_t msg_controllen; /* length of ancillary data */
int msg_flags; /* flags returned by recvmsg() */
};
UNIX Network Programming 11
13.5 recvmsg and sendmsg Functions 13.5 recvmsg and sendmsg Functions (cont.)(cont.)
Flag
Examined by:Send flags
Sendto flagsSendmsg flags
Examined by:recv flags
recvfrom flagsrecvmsg flags
Returned by:
Recvmsg msg_flagsMSG_DONTROUTEMSG_DONTWAITMSG_PEEKMSG_WAITALL
MSG_EORMSG_OOB
MSG_BCASTMSG_MCASTMSG_TRUNCMSG_CTRUNC
Figure 13.7 Summary of input and output flags by various I/O functions
UNIX Network Programming 12
13.5 recvmsg and sendmsg Functions 13.5 recvmsg and sendmsg Functions (cont.)(cont.)
16
0
20
3
msg_name
msg_ flagsmsg_con tro llenmsg_con tro lm sg_ iov lenmsg_ iovmsg_name len
100
60
80
io v_base
iov_ leniov_baseiov_ leniov_baseiov_ len
iovec{}
F igure 13.8 Data structures when recvmsg is called for a UDP socket.
msghdr{}
UNIX Network Programming 13
13.5 recvmsg and sendmsg Functions 13.5 recvmsg and sendmsg Functions (cont.)(cont.)
16
0
20
3
msg_name
msg_ flagsmsg_con tro llenmsg_con tro lm sg_ iov lenmsg_ iovmsg_name len
100
60
80
io v_base
iov_ leniov_baseiov_ leniov_baseiov_ len
iovec{} [ ]
F igure 13.9 Update o f F igure 13.8 when recvmsg return.
msghdr{}
cmsg_ typecmsg_ leve lcm sg_ len
sockaddr_ in{}16, AF_ INET, 2000
198.69.10.2
16IPPROTP_ IPIP_RECVDSTADDR206 .62 .226 .35
UNIX Network Programming 14
13.6 Ancillary Data13.6 Ancillary Data
• Ancillary data can be sent and received using the msg_control and msg_controllen members of the msghdr structure with sendmsg and recvmsg functions.
Protocol cmsg_level Cmsg_type DescriptionIPv4 IPPROTO_IP IP_RECVDSTADDR
IP_RECVIFreceive destination address with UDP datagramreceive interface index with UDP datagram
IPv6 IPPROTO_IPV6 IPV6_DSTOPTSIPV6_HOPLIMITIPV6_HOPOPTSIPV6_NEXTHOPIPV6_PKTINFOIPV6_RTHDR
specify / receive destination optionsspecify / receive hop limitspecify / receive hop-by-hop optionsspecify next-hop addressspecify / receive packet informationspecify / receive routing header
Unix domain SOL_SOCKET SCM_RIGHTSSCM_CREDS
send / receive descriptorssend / receive user credentials
Figure 13.11 summary of uses for ancillary data.
UNIX Network Programming 15
13.6 Ancillary Data 13.6 Ancillary Data (cont.)(cont.)
cmsg_len
cmsg_level
cmsg_type
pad
data
pad
cmsg_len
cmsg_level
cmsg_type
pad
data
c msghdr{}
c msghdr{}
ac c illarydata objec t
C MSG _ SPAC E ()
ac c illarydata objec t
C MSG _ SPAC E ()
msg_contro l
CM
SG_L
EN()
cmsg
_len
msg
_con
trol
len
cmsg
_len
CM
SG_L
EN()
F igure 13.12 Anc illary data containing two anc illary data objects .
UNIX Network Programming 16
13.6 Ancillary Data 13.6 Ancillary Data (cont.)(cont.)
cmsghdr{}
F igure 13.13 cmsghdr structure when used with Unix domain sockets.
cmsg_len
cmsg_level
cmsg_type
d iscr ip to r
16
SOL_SOCKET
SCM_RIGHTS
cmsghdr{}
cmsg_len
cmsg_level
cmsg_type
16
SOL_SOCKET
SCM_CREDS
fcred{}
UNIX Network Programming 17
13.7 How Much Data Is Queued?13.7 How Much Data Is Queued?
• Three techniques - page 365.
UNIX Network Programming 18
13.8 Sockets and Standard I/O13.8 Sockets and Standard I/O
• The standard I/O stream can be used with sockets, but there are a few items to consider.
– A standard I/O stream can be created from any desciptor by calling the fdopen function. Similarly, given a standard I/O stream, we can obtain the corresponding descriptor by calling fileno.
– fseek, fsetpos, rewind functions is that they all call lseek, which fails on a socket.
– The easiest way to handle this read-write problem is to open two standard I/O streams for a given socket: one for reading, and one for writing.
UNIX Network Programming 19
13.8 Sockets and Standard I/O13.8 Sockets and Standard I/O
• Example : str_echo Function using standard I/O
#include "unp.h"
voidstr_echo(int sockfd){
char line[MAXLINE];FILE *fpin, *fpout;
fpin = Fdopen(sockfd, "r");fpout = Fdopen(sockfd, "w");
for ( ; ; ) {if (Fgets(line, MAXLINE, fpin) == NULL) return; /* connection closed by other end */
Fputs(line, fpout);}
}
UNIX Network Programming 20
13.9 T/TCP: TCP for Transactions13.9 T/TCP: TCP for Transactions
• T/TCP is a slight modification to TCP that can avoid the three-way handshake between hosts that have communicated with each other recently.
• Benefit
– all the reliability of TCP is retained
– maintains TCP’s slow start and congestion avoidance, features that are often missing from UDP applications.
UNIX Network Programming 21
13.9 T/TCP: TCP for Transactions 13.9 T/TCP: TCP for Transactions (cont.)(cont.)
c lient server
socketsendto
read(blocks)
read returns
accept returnsread request<server proc esses reques t>
send replyc lose
Figure 13.15 Time line o f minimal T/ TC P transaction
socket, bind,listenaccept(blocks)
top related