xref: /csrg-svn/lib/libc/net/gethostnamadr.c (revision 15756)
1 /*	gethostnamadr.c	4.2	83/12/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 char HOSTDB[] = "/etc/hosts";
11 static DBM *db = (DBM *)NULL;
12 static datum curkey;
13 static struct hostent host;
14 static char *host_aliases[MAXALIASES];
15 extern int _stayopen;	/* set by sethostent(), cleared by endhostent() */
16 
17 static struct hostent *
18 fetchhost(key)
19 	datum key;
20 {
21         register char *cp, **ap;
22 	register int naliases;
23 
24         curkey = key;
25         if (curkey.dptr == 0)
26                 return ((struct hostent *)NULL);
27 	key = dbmfetch(db, curkey);
28 	if (key.dptr == 0)
29                 return ((struct hostent *)NULL);
30         cp = key.dptr;
31 	host.h_name = cp;
32 	while (*cp++)
33 		;
34 	naliases = *(int *)cp; cp += sizeof (int);
35 	for (ap = host_aliases; naliases > 0; naliases--) {
36 		*ap++ = cp;
37 		while (*cp++)
38 			;
39 	}
40 	*ap = (char *)NULL;
41 	host.h_aliases = host_aliases;
42 	host.h_addrtype = *(int *)cp; cp += sizeof (int);
43 	host.h_length = *(int *)cp; cp += sizeof (int);
44 	host.h_addr = cp;
45         return (&host);
46 }
47 
48 struct hostent *
49 gethostbyname(nam)
50 	char *nam;
51 {
52         datum key;
53 	register struct hostent *hp;
54 
55 	if (db == (DBM *)0 && (db = ndbmopen(HOSTDB, O_RDONLY)) == (DBM *)0)
56                 return ((struct hostent *)NULL);
57         key.dptr = nam;
58         key.dsize = strlen(nam);
59 	hp = fetchhost(key);
60 	if (!_stayopen) {
61 		ndbmclose(db);
62 		db = (DBM *)NULL;
63 	}
64         return (hp);
65 }
66 
67 struct hostent *
68 gethostbyaddr(addr, length)
69 	char *addr;
70 	int length;
71 {
72         datum key;
73 	register struct hostent *hp;
74 
75 	if (db == (DBM *)0 && (db = ndbmopen(HOSTDB, O_RDONLY)) == (DBM *)0)
76                 return ((struct hostent *)NULL);
77         key.dptr = addr;
78         key.dsize = length;
79 	hp = fetchhost(key);
80 	if (!_stayopen) {
81 		ndbmclose(db);
82 		db = (DBM *)NULL;
83 	}
84         return (hp);
85 }
86