xref: /original-bsd/lib/libc/net/inet_network.c (revision a91856c6)
1 /*
2  * Copyright (c) 1983 Regents of the University of California.
3  * All rights reserved.
4  *
5  * %sccs.include.redist.c%
6  */
7 
8 #if defined(LIBC_SCCS) && !defined(lint)
9 static char sccsid[] = "@(#)inet_network.c	5.8 (Berkeley) 02/24/91";
10 #endif /* LIBC_SCCS and not lint */
11 
12 #include <sys/types.h>
13 #include <netinet/in.h>
14 #include <arpa/inet.h>
15 #include <ctype.h>
16 
17 /*
18  * Internet network address interpretation routine.
19  * The library routines call this routine to interpret
20  * network numbers.
21  */
22 u_long
23 inet_network(cp)
24 	register const char *cp;
25 {
26 	register u_long val, base, n;
27 	register char c;
28 	u_long parts[4], *pp = parts;
29 	register int i;
30 
31 again:
32 	val = 0; base = 10;
33 	if (*cp == '0')
34 		base = 8, cp++;
35 	if (*cp == 'x' || *cp == 'X')
36 		base = 16, cp++;
37 	while (c = *cp) {
38 		if (isdigit(c)) {
39 			val = (val * base) + (c - '0');
40 			cp++;
41 			continue;
42 		}
43 		if (base == 16 && isxdigit(c)) {
44 			val = (val << 4) + (c + 10 - (islower(c) ? 'a' : 'A'));
45 			cp++;
46 			continue;
47 		}
48 		break;
49 	}
50 	if (*cp == '.') {
51 		if (pp >= parts + 4)
52 			return (INADDR_NONE);
53 		*pp++ = val, cp++;
54 		goto again;
55 	}
56 	if (*cp && !isspace(*cp))
57 		return (INADDR_NONE);
58 	*pp++ = val;
59 	n = pp - parts;
60 	if (n > 4)
61 		return (INADDR_NONE);
62 	for (val = 0, i = 0; i < n; i++) {
63 		val <<= 8;
64 		val |= parts[i] & 0xff;
65 	}
66 	return (val);
67 }
68