1/* $NetBSD$ */ 2 3#include <stdio.h> 4#include <strings.h> 5#include <errno.h> 6#include <sys/types.h> 7#include <sys/time.h> 8#include <netinet/in.h> 9#include <netdb.h> 10#include "arlib.h" 11 12#ifndef lint 13static char sccsid[] = "@(#)sample.c 1.1 12/21/92 (C)1992 Darren Reed. ASYNC DNS"; 14#endif 15 16char line[512]; 17 18int lookup = 0, seq = 0; 19long expire = 0; 20 21main() 22{ 23 struct in_addr adr; 24 struct timeval tv2; 25 fd_set rd; 26 long now; 27 char *s; 28 int afd, nfd, pid = getpid(), del; 29 30 afd = ar_init(ARES_INITLIST|ARES_CALLINIT|ARES_INITSOCK); 31 32 (void)printf("afd = %d pid = %d\n",afd, pid); 33 34 while (1) 35 { 36 (void)printf("Host =>"); 37 (void)fflush(stdout); 38 *line = '\0'; 39 FD_ZERO(&rd); 40 FD_SET(0,&rd); 41 FD_SET(afd,&rd); 42 now = time(NULL); 43 if (expire >= now) 44 { 45 tv2.tv_usec = 0; 46 tv2.tv_sec = expire - now; 47 nfd = select(FD_SETSIZE, &rd, NULL, NULL, &tv2); 48 } 49 else 50 nfd = select(FD_SETSIZE, &rd, NULL, NULL, NULL); 51 52 if (FD_ISSET(0, &rd)) 53 { 54 if (!fgets(line, sizeof(line) - 1, stdin)) 55 exit(0); 56 if (s = index(line, '\n')) 57 *s = '\0'; 58 } 59 60 if (isalpha(*line)) 61 { 62 (void)printf("Asking about [%s] #%d.\n",line, ++seq); 63 (void)ar_gethostbyname(line, (char *)&seq, 64 sizeof(seq)); 65 lookup++; 66 } 67 else if (isdigit(*line)) 68 { 69 (void)printf("Asking about IP#[%s] #%d.\n", 70 line, ++seq); 71 adr.s_addr = inet_addr(line); 72 (void)ar_gethostbyaddr(&adr, (char *)&seq, 73 sizeof(seq)); 74 lookup++; 75 } 76 if (lookup) 77 (void)printf("Waiting for answer:\n"); 78 if (FD_ISSET(afd, &rd)) 79 (void)waitonlookup(afd); 80 del = 0; 81 expire = ar_timeout(time(NULL), &del, sizeof(del)); 82 if (del) 83 { 84 (void)fprintf(stderr,"#%d failed\n", del); 85 lookup--; 86 } 87 } 88} 89 90printhostent(hp) 91struct hostent *hp; 92{ 93 struct in_addr ip; 94 int i; 95 96 (void)printf("hname = %s\n", hp->h_name); 97 for (i = 0; hp->h_aliases[i]; i++) 98 (void)printf("alias %d = %s\n", i+1, hp->h_aliases[i]); 99 for (i = 0; hp->h_addr_list[i]; i++) 100 { 101 bcopy(hp->h_addr_list[i], (char *)&ip, sizeof(ip)); 102 (void)printf("IP# %d = %s\n", i+1, inet_ntoa(ip)); 103 } 104} 105 106int waitonlookup(afd) 107int afd; 108{ 109 struct timeval delay; 110 struct hostent *hp; 111 fd_set rd; 112 long now; 113 int nfd, del; 114 115waitloop: 116 FD_ZERO(&rd); 117 now = time(NULL); 118 if (expire >= now) 119 delay.tv_sec = expire - now; 120 else 121 delay.tv_sec = 1; 122 delay.tv_usec = 0; 123 FD_SET(afd, &rd); 124 FD_SET(0, &rd); 125 126 nfd = select(FD_SETSIZE, &rd, 0, 0, &delay); 127 if (nfd == 0) 128 return 0; 129 else if (FD_ISSET(afd, &rd)) 130 { 131 del = 0; 132 hp = ar_answer(&del, sizeof(del)); 133 134 (void)printf("hp=%x seq=%d\n",hp,del); 135 if (hp) 136 { 137 (void)printhostent(hp); 138 if (!--lookup) 139 return 1; 140 } 141 } 142 if (FD_ISSET(0, &rd)) 143 return 2; 144 return 0; 145} 146