#include #include #include #include #include #include #include #include #include int main(int argc, char *argv[]) { int sock; struct sockaddr_in saddr; struct hostent *shost; struct servent *serv; char *host, buf[256]; char *p; if (argc == 1) { if ((host = getenv("DAYTIMESERVER")) == NULL) host = "localhost"; } else { host = argv[1]; } if ((serv = getservbyname("daytime", "tcp")) == NULL) { fprintf(stderr, "unknown service: daytime/tcp\n"); return EXIT_FAILURE; } memset(&saddr, 0, sizeof(saddr)); if (isdigit(*host)) { saddr.sin_addr.s_addr = inet_addr(host); if ((shost = gethostbyaddr((char *)&saddr.sin_addr, sizeof(saddr.sin_addr), AF_INET)) == NULL) { fprintf(stderr, "gethostbyaddr() failed.\n"); return EXIT_FAILURE; } host = shost->h_name; } else { shost = gethostbyname(host); if (shost) { memcpy(&saddr.sin_addr, shost->h_addr, shost->h_length); } else { fprintf(stderr, "%s: host name lookup failed.\n", host); return EXIT_FAILURE; } } saddr.sin_family = AF_INET; saddr.sin_port = htons(serv->s_port); if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) { fprintf(stderr, "can't create socket.\n"); return 1; } if (connect(sock, (struct sockaddr *)&saddr, sizeof(struct sockaddr)) < 0) { fprintf(stderr, "%s: unable to connect: %s\n", host, strerror(errno)); return EXIT_FAILURE; } read(sock, buf, sizeof(buf)); for (p = buf; *p; p++) { if (*p == '\n') { *++p = '\0'; break; } } printf("%s", buf); close(sock); return EXIT_SUCCESS; }