xref: /csrg-svn/lib/libc/net/getnetent.c (revision 26618)
1 /*
2  * Copyright (c) 1983 Regents of the University of California.
3  * All rights reserved.  The Berkeley software License Agreement
4  * specifies the terms and conditions for redistribution.
5  */
6 
7 #if defined(LIBC_SCCS) && !defined(lint)
8 static char sccsid[] = "@(#)getnetent.c	5.2 (Berkeley) 03/09/86";
9 #endif LIBC_SCCS and not lint
10 
11 #include <stdio.h>
12 #include <sys/types.h>
13 #include <sys/socket.h>
14 #include <netdb.h>
15 #include <ctype.h>
16 
17 #define	MAXALIASES	35
18 
19 static char NETDB[] = "/etc/networks";
20 static FILE *netf = NULL;
21 static char line[BUFSIZ+1];
22 static struct netent net;
23 static char *net_aliases[MAXALIASES];
24 static int stayopen = 0;
25 static char *any();
26 
27 setnetent(f)
28 	int f;
29 {
30 	if (netf == NULL)
31 		netf = fopen(NETDB, "r" );
32 	else
33 		rewind(netf);
34 	stayopen |= f;
35 }
36 
37 endnetent()
38 {
39 	if (netf && !stayopen) {
40 		fclose(netf);
41 		netf = NULL;
42 	}
43 }
44 
45 struct netent *
46 getnetent()
47 {
48 	char *p;
49 	register char *cp, **q;
50 
51 	if (netf == NULL && (netf = fopen(NETDB, "r" )) == NULL)
52 		return (NULL);
53 again:
54 	p = fgets(line, BUFSIZ, netf);
55 	if (p == NULL)
56 		return (NULL);
57 	if (*p == '#')
58 		goto again;
59 	cp = any(p, "#\n");
60 	if (cp == NULL)
61 		goto again;
62 	*cp = '\0';
63 	net.n_name = p;
64 	cp = any(p, " \t");
65 	if (cp == NULL)
66 		goto again;
67 	*cp++ = '\0';
68 	while (*cp == ' ' || *cp == '\t')
69 		cp++;
70 	p = any(cp, " \t");
71 	if (p != NULL)
72 		*p++ = '\0';
73 	net.n_net = inet_network(cp);
74 	net.n_addrtype = AF_INET;
75 	q = net.n_aliases = net_aliases;
76 	if (p != NULL)
77 		cp = p;
78 	while (cp && *cp) {
79 		if (*cp == ' ' || *cp == '\t') {
80 			cp++;
81 			continue;
82 		}
83 		if (q < &net_aliases[MAXALIASES - 1])
84 			*q++ = cp;
85 		cp = any(cp, " \t");
86 		if (cp != NULL)
87 			*cp++ = '\0';
88 	}
89 	*q = NULL;
90 	return (&net);
91 }
92 
93 static char *
94 any(cp, match)
95 	register char *cp;
96 	char *match;
97 {
98 	register char *mp, c;
99 
100 	while (c = *cp) {
101 		for (mp = match; *mp; mp++)
102 			if (*mp == c)
103 				return (cp);
104 		cp++;
105 	}
106 	return ((char *)0);
107 }
108