wangzhengquan
2020-12-30 5eced9fa401e05226309ec9682df4310b18683c3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
 
 
/* is_seqnum_cl.c
 
   A simple Internet stream socket client. This client requests a sequence
   number from the server.
 
   See also is_seqnum_sv.c.
*/
#include <netdb.h>
#include "is_seqnum.h"
 
int
main(int argc, char *argv[])
{
    char request[1024];                    /* Requested length of sequence */
    char response[1024];
    int cfd;
    ssize_t numRead;
    struct addrinfo hints;
    struct addrinfo *result, *rp;
 
    if (argc < 2 || strcmp(argv[1], "--help") == 0)
        printf("%s server-host\n", argv[0]);
 
    /* Call getaddrinfo() to obtain a list of addresses that
       we can try connecting to */
 
    memset(&hints, 0, sizeof(struct addrinfo));
    hints.ai_canonname = NULL;
    hints.ai_addr = NULL;
    hints.ai_next = NULL;
    hints.ai_family = AF_UNSPEC;                /* Allows IPv4 or IPv6 */
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_NUMERICSERV;
 
    if (getaddrinfo(argv[1], PORT_NUM, &hints, &result) != 0)
        err_exit(errno, "getaddrinfo");
 
    /* Walk through returned list until we find an address structure
       that can be used to successfully connect a socket */
 
    for (rp = result; rp != NULL; rp = rp->ai_next) {
        cfd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
        if (cfd == -1)
            continue;                           /* On error, try next address */
 
        if (connect(cfd, rp->ai_addr, rp->ai_addrlen) != -1)
            break;                              /* Success */
 
        /* Connect failed: close this socket and try next address */
 
        close(cfd);
    }
 
    if (rp == NULL)
        err_exit(errno, "Could not connect socket to any address");
 
    freeaddrinfo(result);
 
    /* Send requested sequence length, with terminating newline */
 
    fputs("request:", stdout);
    if(fgets(request, 1024, stdin) != NULL) {
      if (write(cfd, request, strlen(request)) !=  strlen(request))
        err_exit(errno, "Partial/failed write (reqLenStr)");
 
        numRead = readLine(cfd, response, 1024);
        if (numRead == -1)
            err_exit(errno, "readLine");
        if (numRead == 0)
            err_exit(errno, "Unexpected EOF from server");
 
        printf("response: %s", response);   /* Includes '\n' */
        puts("request:");
    }
    exit(EXIT_SUCCESS);
}