1 /*	gethostent.c	4.3	82/11/14	*/
2 
3 #include <stdio.h>
4 #include <sys/types.h>
5 #include <sys/socket.h>
6 #include <netdb.h>
7 #include <ctype.h>
8 
9 /*
10  * Internet version.
11  */
12 #define	MAXALIASES	35
13 #define	MAXADDRSIZE	14
14 
15 static char HOSTDB[] = "/usr/lib/hosts";
16 static FILE *hostf = NULL;
17 static char line[BUFSIZ+1];
18 static char hostaddr[MAXADDRSIZE];
19 static struct hostent host;
20 static char *host_aliases[MAXALIASES];
21 static int stayopen = 0;
22 static char *any();
23 
24 sethostent(f)
25 	int f;
26 {
27 	if (hostf == NULL)
28 		hostf = fopen(HOSTDB, "r" );
29 	else
30 		rewind(hostf);
31 	stayopen |= f;
32 }
33 
34 endhostent()
35 {
36 	if (hostf && !stayopen) {
37 		fclose(hostf);
38 		hostf = NULL;
39 	}
40 }
41 
42 struct hostent *
43 gethostent()
44 {
45 	char *p;
46 	register char *cp, **q;
47 
48 	if (hostf == NULL && (hostf = fopen(HOSTDB, "r" )) == NULL)
49 		return (NULL);
50 again:
51 	if ((p = fgets(line, BUFSIZ, hostf)) == NULL)
52 		return (NULL);
53 	if (*p == '#')
54 		goto again;
55 	cp = any(p, "#\n");
56 	if (cp == NULL)
57 		goto again;
58 	*cp = '\0';
59 	cp = any(p, " \t");
60 	if (cp == NULL)
61 		goto again;
62 	*cp++ = '\0';
63 	/* THIS STUFF IS INTERNET SPECIFIC */
64 	host.h_addr = hostaddr;
65 	*((u_long *)host.h_addr) = inet_addr(p);
66 	host.h_length = sizeof (u_long);
67 	host.h_addrtype = AF_INET;
68 	while (*cp == ' ' || *cp == '\t')
69 		cp++;
70 	host.h_name = cp;
71 	q = host.h_aliases = host_aliases;
72 	cp = any(cp, " \t");
73 	if (cp != NULL) {
74 		*cp++ = '\0';
75 		while (*cp) {
76 			if (*cp == ' ' || *cp == '\t') {
77 				cp++;
78 				continue;
79 			}
80 			if (q < &host_aliases[MAXALIASES - 1])
81 				*q++ = cp;
82 			cp = any(cp, " \t");
83 			if (*cp != NULL)
84 				*cp++ = '\0';
85 		}
86 	}
87 	*q = NULL;
88 	return (&host);
89 }
90 
91 static char *
92 any(cp, match)
93 	register char *cp;
94 	char *match;
95 {
96 	register char *mp, c;
97 
98 	while (c = *cp) {
99 		for (mp = match; *mp; mp++)
100 			if (*mp == c)
101 				return (cp);
102 		cp++;
103 	}
104 	return ((char *)0);
105 }
106