/* 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 #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); }