/* daytimetcpcli.c - From Stevens, Network Programming Vol. 1 with minor changes. Compile with % gcc -o client daytimetcpcli.c Run with % client [hostname [portid]] We use the localhost and port 5000 by default. */ #include #include #include #include #include /* basic system data types */ #include /* basic socket definitions */ #include /* timeval{} for select() */ #include /* timespec{} for pselect() */ #include /* sockaddr_in{} and other Internet defns */ #include /* needed by gethostbyname */ #include /* needed by inet_ntoa */ int main(int argc, char **argv) { int sockfd; int n; char recvline[128 + 1]; struct sockaddr_in servaddr; unsigned short port; char * hostname; struct hostent * hp; hostname = (argc > 1) ? argv[1] : "localhost"; port = (argc > 2) ? atoi(argv[2]) : 5000; if ( (hp = gethostbyname(hostname) ) == 0) { perror("gethostbyname"); exit(0); } if ( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { perror("socket"); exit(1); } bzero((char *)&servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(port); memcpy(&servaddr.sin_addr, hp->h_addr, hp->h_length); if (servaddr.sin_addr.s_addr <= 0) { perror("bad address after gethostbyname"); exit(1); } if (connect(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0) { perror("connect"); exit(1); } while ( (n = read(sockfd, recvline, sizeof(recvline)-1)) > 0) { recvline[n] = 0; /* null terminate */ if (fputs(recvline, stdout) == EOF) { perror("fputs"); exit(1); } } if (n < 0) { perror("read"); exit(1); } exit(0); }