xref: /original-bsd/lib/libc/net/inet_addr.c (revision f0fd5f8a)
1 /*	inet_addr.c	4.5	82/11/14	*/
2 
3 #include <sys/types.h>
4 #include <ctype.h>
5 #include <netinet/in.h>
6 
7 /*
8  * Internet address interpretation routine.
9  * All the network library routines call this
10  * routine to interpret entries in the data bases
11  * which are expected to be an address.
12  * The value returned is in network order.
13  */
14 u_long
15 inet_addr(cp)
16 	register char *cp;
17 {
18 	register u_long val, base, n;
19 	register char c;
20 	u_long parts[4], *pp = parts;
21 
22 again:
23 	/*
24 	 * Collect number up to ``.''.
25 	 * Values are specified as for C:
26 	 * 0x=hex, 0=octal, other=decimal.
27 	 */
28 	val = 0; base = 10;
29 	if (*cp == '0')
30 		base = 8, cp++;
31 	if (*cp == 'x' || *cp == 'X')
32 		base = 16, cp++;
33 	while (c = *cp) {
34 		if (isdigit(c)) {
35 			val = (val * base) + (c - '0');
36 			cp++;
37 			continue;
38 		}
39 		if (base == 16 && isxdigit(c)) {
40 			val = (val << 4) + (c + 10 - (islower(c) ? 'a' : 'A'));
41 			cp++;
42 			continue;
43 		}
44 		break;
45 	}
46 	if (*cp == '.') {
47 		/*
48 		 * Internet format:
49 		 *	a.b.c.d
50 		 *	a.b.c	(with c treated as 16-bits)
51 		 *	a.b	(with b treated as 24 bits)
52 		 */
53 		if (pp >= parts + 4)
54 			return (-1);
55 		*pp++ = val, cp++;
56 		goto again;
57 	}
58 	/*
59 	 * Check for trailing characters.
60 	 */
61 	if (*cp && !isspace(*cp))
62 		return (-1);
63 	*pp++ = val;
64 	/*
65 	 * Concoct the address according to
66 	 * the number of parts specified.
67 	 */
68 	n = pp - parts;
69 	switch (n) {
70 
71 	case 1:				/* a -- 32 bits */
72 		val = parts[0];
73 		break;
74 
75 	case 2:				/* a.b -- 8.24 bits */
76 		val = (parts[0] << 24) | (parts[1] & 0xffffff);
77 		break;
78 
79 	case 3:				/* a.b.c -- 8.8.16 bits */
80 		val = (parts[0] << 24) | ((parts[1] & 0xff) << 16) |
81 			(parts[2] & 0xffff);
82 		break;
83 
84 	case 4:				/* a.b.c.d -- 8.8.8.8 bits */
85 		val = (parts[0] << 24) | ((parts[1] & 0xff) << 16) |
86 		      ((parts[2] & 0xff) << 8) | (parts[3] & 0xff);
87 		break;
88 
89 	default:
90 		return (-1);
91 	}
92 	val = htonl(val);
93 	return (val);
94 }
95