1 /* gethostnamadr.c 4.6 85/01/10 */ 2 3 #include <stdio.h> 4 #include <netdb.h> 5 #include <sys/file.h> 6 #include <ndbm.h> 7 8 #define MAXALIASES 35 9 10 static char HOSTDB[] = "/etc/hosts"; 11 DBM *_host_db = (DBM *)NULL; 12 static struct hostent host; 13 static char *host_aliases[MAXALIASES]; 14 static char hostbuf[BUFSIZ+1]; 15 int _host_stayopen; /* set by sethostent(), cleared by endhostent() */ 16 17 static struct hostent * 18 fetchhost(key) 19 datum key; 20 { 21 register char *cp, *tp, **ap; 22 register int naliases; 23 24 if (key.dptr == 0) 25 return ((struct hostent *)NULL); 26 key = dbm_fetch(_host_db, key); 27 if (key.dptr == 0) 28 return ((struct hostent *)NULL); 29 cp = key.dptr; 30 tp = hostbuf; 31 host.h_name = tp; 32 while (*tp++ = *cp++) 33 ; 34 naliases = *(int *)cp; cp += sizeof (int); 35 for (ap = host_aliases; naliases > 0; naliases--) { 36 *ap++ = tp; 37 while (*tp++ = *cp++) 38 ; 39 } 40 *ap = (char *)NULL; 41 host.h_aliases = host_aliases; 42 bcopy(cp, (char *)&host.h_addrtype, sizeof (int)); 43 cp += sizeof (int); 44 bcopy(cp, (char *)&host.h_length, sizeof (int)); 45 cp += sizeof (int); 46 host.h_addr = tp; 47 bcopy(cp, tp, host.h_length); 48 return (&host); 49 } 50 51 struct hostent * 52 gethostbyname(nam) 53 char *nam; 54 { 55 datum key; 56 register struct hostent *hp; 57 58 if ((_host_db == (DBM *)NULL) 59 && ((_host_db = dbm_open(HOSTDB, O_RDONLY)) == (DBM *)NULL)) 60 return ((struct hostent *)NULL); 61 key.dptr = nam; 62 key.dsize = strlen(nam); 63 hp = fetchhost(key); 64 if (!_host_stayopen) { 65 dbm_close(_host_db); 66 _host_db = (DBM *)NULL; 67 } 68 return (hp); 69 } 70 71 struct hostent * 72 gethostbyaddr(addr, length) 73 char *addr; 74 int length; 75 { 76 datum key; 77 register struct hostent *hp; 78 79 if ((_host_db == (DBM *)NULL) 80 && ((_host_db = dbm_open(HOSTDB, O_RDONLY)) == (DBM *)NULL)) 81 return ((struct hostent *)NULL); 82 key.dptr = addr; 83 key.dsize = length; 84 hp = fetchhost(key); 85 if (!_host_stayopen) { 86 dbm_close(_host_db); 87 _host_db = (DBM *)NULL; 88 } 89 return (hp); 90 } 91