1 /*	gethostnamadr.c	4.7	85/01/21	*/
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 struct hostent host;
11 static char *host_aliases[MAXALIASES];
12 static char hostbuf[BUFSIZ+1];
13 
14 /*
15  * The following is shared with gethostent.c
16  */
17 extern	char *_host_file;
18 DBM	*_host_db = (DBM *)NULL;
19 int	_host_stayopen;	/* set by sethostent(), cleared by endhostent() */
20 
21 static struct hostent *
22 fetchhost(key)
23 	datum key;
24 {
25         register char *cp, *tp, **ap;
26 	register int naliases;
27 
28         if (key.dptr == 0)
29                 return ((struct hostent *)NULL);
30 	key = dbm_fetch(_host_db, key);
31 	if (key.dptr == 0)
32                 return ((struct hostent *)NULL);
33         cp = key.dptr;
34 	tp = hostbuf;
35 	host.h_name = tp;
36 	while (*tp++ = *cp++)
37 		;
38 	naliases = *(int *)cp; cp += sizeof (int);
39 	for (ap = host_aliases; naliases > 0; naliases--) {
40 		*ap++ = tp;
41 		while (*tp++ = *cp++)
42 			;
43 	}
44 	*ap = (char *)NULL;
45 	host.h_aliases = host_aliases;
46 	bcopy(cp, (char *)&host.h_addrtype, sizeof (int));
47 	cp += sizeof (int);
48 	bcopy(cp, (char *)&host.h_length, sizeof (int));
49 	cp += sizeof (int);
50 	host.h_addr = tp;
51 	bcopy(cp, tp, host.h_length);
52         return (&host);
53 }
54 
55 struct hostent *
56 gethostbyname(nam)
57 	register char *nam;
58 {
59 	register struct hostent *hp;
60 	register char **cp;
61         datum key;
62 
63 	if ((_host_db == (DBM *)NULL)
64 	  && ((_host_db = dbm_open(_host_file, O_RDONLY)) == (DBM *)NULL)) {
65 		sethostent(_host_stayopen);
66 		while (hp = gethostent()) {
67 			if (strcmp(hp->h_name, nam) == 0)
68 				break;
69 			for (cp = hp->h_aliases; cp != 0 && *cp != 0; cp++)
70 				if (strcmp(*cp, nam) == 0)
71 					goto found;
72 		}
73 	found:
74 		if (!_host_stayopen)
75 			endhostent();
76 		return (hp);
77 	}
78         key.dptr = nam;
79         key.dsize = strlen(nam);
80 	hp = fetchhost(key);
81 	if (!_host_stayopen) {
82 		dbm_close(_host_db);
83 		_host_db = (DBM *)NULL;
84 	}
85         return (hp);
86 }
87 
88 struct hostent *
89 gethostbyaddr(addr, length, type)
90 	char *addr;
91 	register int length;
92 	register int type;
93 {
94 	register struct hostent *hp;
95         datum key;
96 
97 	if ((_host_db == (DBM *)NULL)
98 	  && ((_host_db = dbm_open(_host_file, O_RDONLY)) == (DBM *)NULL)) {
99 		sethostent(_host_stayopen);
100 		while (hp = gethostent()) {
101 			if (hp->h_addrtype == type && hp->h_length == length
102 			    && bcmp(hp->h_addr, addr, length) == 0)
103 				break;
104 		}
105 		if (!_host_stayopen)
106 			endhostent();
107 		return (hp);
108 	}
109         key.dptr = addr;
110         key.dsize = length;
111 	hp = fetchhost(key);
112 	if (!_host_stayopen) {
113 		dbm_close(_host_db);
114 		_host_db = (DBM *)NULL;
115 	}
116         return (hp);
117 }
118