#include #include #include /* for getservbyname */ #include #include #include #include int main(int argc, char **argv) { struct sockaddr_in address; char buffer[INET_ADDRSTRLEN]; /* for inet_pton */ struct hostent *entry; /* for gethostbyname, gethostbyaddr */ int s; /* file descriptor */ bzero((char *)&address, sizeof address); address.sin_family = AF_INET; if (argc == 2) { /* one command line argument */ const struct servent *const p = getservbyname("telnet", "tcp"); if (p == NULL) { fprintf(stderr, "%s: couldn't find telnet port number\n", argv[0]); return 1; } address.sin_port = p->s_port; } else if (argc == 3) { /* two command line arguments */ if (sscanf(argv[2], "%hd", &address.sin_port) != 1) { fprintf(stderr, "%s: %s is not a legal port number\n", argv[0], argv[2]); return 2; } address.sin_port = htons(address.sin_port); } else { fprintf(stderr, "%s: usage hostname [port]\n", argv[0]); return 3; } entry = gethostbyname(argv[1]); if (entry == NULL) { fprintf(stderr, "%s: gethostbyname, h_errno == %d\n", argv[0], h_errno); return 4; } address.sin_addr.s_addr = *(in_addr_t *)entry->h_addr_list[0]; s = socket(AF_INET, SOCK_STREAM, 0); if (s < 0) { perror(argv[0]); return 5; } if (inet_ntop(AF_INET, &address.sin_addr, buffer, sizeof buffer) == NULL) { perror(argv[0]); return 6; } printf("Trying %s...\n", buffer); if (connect(s, (struct sockaddr *)&address, sizeof address) != 0) { perror(argv[0]); return 7; } entry = gethostbyaddr((char *)&address.sin_addr, sizeof address.sin_addr, AF_INET); if (entry == NULL) { fprintf(stderr, "%s: gethostbyaddr, h_errno == %d\n", argv[0], h_errno); return 8; } printf("Connected to %s.\n", entry->h_name); for (;;) { fd_set readset; /* set of file descriptors */ struct timeval t = {0, 0}; /* seconds, microseconds */ char c; int n; FD_ZERO(&readset); FD_SET(s, &readset); FD_SET(fileno(stdin), &readset); if (select(s + 1, &readset, NULL, NULL, &t) < 0) { perror(argv[0]); return 9; } if (FD_ISSET(s, &readset)) { /* We can call the following read without getting stuck. */ n = read(s, &c, 1); if (n < 0) { perror(argv[0]); return 10; } if (n == 0) { /* Received end of file from the server */ printf("Connection closed by foreign host.\n"); break; } if (write(fileno(stdout), &c, 1) != 1) { perror(argv[0]); return 11; } } if (FD_ISSET(fileno(stdin), &readset)) { /* We can call the following read without getting stuck. */ n = read(fileno(stdin), &c, 1); if (n < 0) { perror(argv[0]); return 12; } if (n == 0) { /* Received end of file from the stdin. */ printf("Connection closed.\n"); break; } if (write(s, &c, 1) != 1) { perror(argv[0]); return 13; } } } if (shutdown(s, SHUT_RDWR) != 0) { perror(argv[0]); return 11; } return EXIT_SUCCESS; }