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