xref: /original-bsd/lib/libc/net/getnetent.c (revision 31205e5f)
1 /*
2  * Copyright (c) 1983 Regents of the University of California.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms are permitted
6  * provided that the above copyright notice and this paragraph are
7  * duplicated in all such forms and that any documentation,
8  * advertising materials, and other materials related to such
9  * distribution and use acknowledge that the software was developed
10  * by the University of California, Berkeley.  The name of the
11  * University may not be used to endorse or promote products derived
12  * from this software without specific prior written permission.
13  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
14  * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
15  * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
16  */
17 
18 #if defined(LIBC_SCCS) && !defined(lint)
19 static char sccsid[] = "@(#)getnetent.c	5.5 (Berkeley) 06/27/88";
20 #endif /* LIBC_SCCS and not lint */
21 
22 #include <stdio.h>
23 #include <sys/types.h>
24 #include <sys/socket.h>
25 #include <netdb.h>
26 #include <ctype.h>
27 
28 #define	MAXALIASES	35
29 
30 static char NETDB[] = "/etc/networks";
31 static FILE *netf = NULL;
32 static char line[BUFSIZ+1];
33 static struct netent net;
34 static char *net_aliases[MAXALIASES];
35 int _net_stayopen;
36 static char *any();
37 
38 setnetent(f)
39 	int f;
40 {
41 	if (netf == NULL)
42 		netf = fopen(NETDB, "r" );
43 	else
44 		rewind(netf);
45 	_net_stayopen |= f;
46 }
47 
48 endnetent()
49 {
50 	if (netf) {
51 		fclose(netf);
52 		netf = NULL;
53 	}
54 	_net_stayopen = 0;
55 }
56 
57 struct netent *
58 getnetent()
59 {
60 	char *p;
61 	register char *cp, **q;
62 
63 	if (netf == NULL && (netf = fopen(NETDB, "r" )) == NULL)
64 		return (NULL);
65 again:
66 	p = fgets(line, BUFSIZ, netf);
67 	if (p == NULL)
68 		return (NULL);
69 	if (*p == '#')
70 		goto again;
71 	cp = any(p, "#\n");
72 	if (cp == NULL)
73 		goto again;
74 	*cp = '\0';
75 	net.n_name = p;
76 	cp = any(p, " \t");
77 	if (cp == NULL)
78 		goto again;
79 	*cp++ = '\0';
80 	while (*cp == ' ' || *cp == '\t')
81 		cp++;
82 	p = any(cp, " \t");
83 	if (p != NULL)
84 		*p++ = '\0';
85 	net.n_net = inet_network(cp);
86 	net.n_addrtype = AF_INET;
87 	q = net.n_aliases = net_aliases;
88 	if (p != NULL)
89 		cp = p;
90 	while (cp && *cp) {
91 		if (*cp == ' ' || *cp == '\t') {
92 			cp++;
93 			continue;
94 		}
95 		if (q < &net_aliases[MAXALIASES - 1])
96 			*q++ = cp;
97 		cp = any(cp, " \t");
98 		if (cp != NULL)
99 			*cp++ = '\0';
100 	}
101 	*q = NULL;
102 	return (&net);
103 }
104 
105 static char *
106 any(cp, match)
107 	register char *cp;
108 	char *match;
109 {
110 	register char *mp, c;
111 
112 	while (c = *cp) {
113 		for (mp = match; *mp; mp++)
114 			if (*mp == c)
115 				return (cp);
116 		cp++;
117 	}
118 	return ((char *)0);
119 }
120