xref: /csrg-svn/lib/libc/net/getprotoent.c (revision 12691)
1 /*	getprotoent.c	4.6	83/05/23	*/
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 #define	MAXALIASES	35
10 
11 static char PROTODB[] = "/etc/protocols";
12 static FILE *protof = NULL;
13 static char line[BUFSIZ+1];
14 static struct protoent proto;
15 static char *proto_aliases[MAXALIASES];
16 static int stayopen = 0;
17 static char *any();
18 
19 setprotoent(f)
20 	int f;
21 {
22 	if (protof == NULL)
23 		protof = fopen(PROTODB, "r" );
24 	else
25 		rewind(protof);
26 	stayopen |= f;
27 }
28 
29 endprotoent()
30 {
31 	if (protof && !stayopen) {
32 		fclose(protof);
33 		protof = NULL;
34 	}
35 }
36 
37 struct protoent *
38 getprotoent()
39 {
40 	char *p;
41 	register char *cp, **q;
42 
43 	if (protof == NULL && (protof = fopen(PROTODB, "r" )) == NULL)
44 		return (NULL);
45 again:
46 	if ((p = fgets(line, BUFSIZ, protof)) == NULL)
47 		return (NULL);
48 	if (*p == '#')
49 		goto again;
50 	cp = any(p, "#\n");
51 	if (cp == NULL)
52 		goto again;
53 	*cp = '\0';
54 	proto.p_name = p;
55 	cp = any(p, " \t");
56 	if (cp == NULL)
57 		goto again;
58 	*cp++ = '\0';
59 	while (*cp == ' ' || *cp == '\t')
60 		cp++;
61 	p = any(cp, " \t");
62 	if (p != NULL)
63 		*p++ = '\0';
64 	proto.p_proto = atoi(cp);
65 	q = proto.p_aliases = proto_aliases;
66 	if (p != NULL) {
67 		cp = p;
68 		while (cp && *cp) {
69 			if (*cp == ' ' || *cp == '\t') {
70 				cp++;
71 				continue;
72 			}
73 			if (q < &proto_aliases[MAXALIASES - 1])
74 				*q++ = cp;
75 			cp = any(cp, " \t");
76 			if (cp != NULL)
77 				*cp++ = '\0';
78 		}
79 	}
80 	*q = NULL;
81 	return (&proto);
82 }
83 
84 static char *
85 any(cp, match)
86 	register char *cp;
87 	char *match;
88 {
89 	register char *mp, c;
90 
91 	while (c = *cp) {
92 		for (mp = match; *mp; mp++)
93 			if (*mp == c)
94 				return (cp);
95 		cp++;
96 	}
97 	return ((char *)0);
98 }
99