1 2 #ifndef lint 3 static char sccsid[] = "@(#)gettable.c 4.3 (Berkeley) 10/05/83"; 4 #endif 5 6 #include <sys/types.h> 7 #include <sys/socket.h> 8 9 #include <netinet/in.h> 10 11 #include <stdio.h> 12 #include <netdb.h> 13 14 #define OUTFILE "hosts.txt" /* default output file */ 15 #define QUERY "ALL\r\n" /* query to hostname server */ 16 17 #define equaln(s1, s2, n) (!strncmp(s1, s2, n)) 18 19 struct sockaddr_in sin; 20 char buf[BUFSIZ]; 21 char *outfile = OUTFILE; 22 23 main(argc, argv) 24 int argc; 25 char *argv[]; 26 { 27 int s; 28 register len; 29 register FILE *sfi, *sfo, *hf; 30 register char *p; 31 char *host; 32 register struct hostent *hp; 33 struct servent *sp; 34 35 argv++, argc--; 36 if (argc < 1 || argc > 2) { 37 fprintf(stderr, "usage: gettable host [ file ]\n"); 38 exit(1); 39 } 40 sp = getservbyname("hostnames", "tcp"); 41 if (sp == NULL) { 42 fprintf(stderr, "gettable: hostnames/tcp: unknown service\n"); 43 exit(3); 44 } 45 host = *argv; 46 argv++, argc--; 47 hp = gethostbyname(host); 48 if (hp == NULL) { 49 fprintf(stderr, "gettable: %s: host unknown\n", host); 50 exit(2); 51 } 52 host = hp->h_name; 53 if (argc > 0) 54 outfile = *argv; 55 sin.sin_family = hp->h_addrtype; 56 s = socket(hp->h_addrtype, SOCK_STREAM, 0, 0); 57 if (s < 0) { 58 perror("gettable: socket"); 59 exit(4); 60 } 61 if (bind(s, &sin, sizeof (sin), 0) < 0) { 62 perror("gettable: bind"); 63 exit(5); 64 } 65 bcopy(hp->h_addr, &sin.sin_addr, hp->h_length); 66 sin.sin_port = sp->s_port; 67 if (connect(s, &sin, sizeof (sin), 0) < 0) { 68 perror("gettable: connect"); 69 exit(6); 70 } 71 fprintf(stderr, "Connection to %s opened.\n", host); 72 sfi = fdopen(s, "r"); 73 sfo = fdopen(s, "w"); 74 if (sfi == NULL || sfo == NULL) { 75 perror("gettable: fdopen"); 76 close(s); 77 exit(1); 78 } 79 hf = fopen(outfile, "w"); 80 if (hf == NULL) { 81 fprintf(stderr, "gettable: "); perror(outfile); 82 close(s); 83 exit(1); 84 } 85 fprintf(sfo, QUERY); 86 fflush(sfo); 87 while (fgets(buf, sizeof(buf), sfi) != NULL) { 88 len = strlen(buf); 89 buf[len-2] = '\0'; 90 if (equaln(buf, "BEGIN", 5) || equaln(buf, "END", 3)) { 91 continue; 92 } 93 if (equaln(buf, "ERR", 3)) { 94 fprintf(stderr, "gettable: hostnames error: %s", buf); 95 continue; 96 } 97 fprintf(hf, "%s\n", buf); 98 } 99 fclose(hf); 100 fprintf(stderr, "Host table received.\n"); 101 close(s); 102 fprintf(stderr, "Connection to %s closed\n", host); 103 } 104