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