xref: /csrg-svn/lib/libc/net/inet_addr.c (revision 8309)
1 /*	inet_addr.c	4.1	82/10/05	*/
2 /*
3  * Internet address interpretation routine.
4  * All the network library routines call this
5  * routine to interpret entries in the data bases
6  * which are expected to be an address.
7  */
8 u_long
9 inet_addr(cp)
10 	register char *cp;
11 {
12 	register unsigned long val, base, n;
13 	register char c;
14 	unsigned long parts[4], *pp = parts;
15 
16 again:
17 	val = 0; base = 10;
18 	if (*cp == '0')
19 		base = 8, cp++;
20 	if (*cp == 'x' || *cp == 'X')
21 		base = 16, cp++;
22 	while (c = *cp) {
23 		if (isdigit(c)) {
24 			val = (val * base) + (c - '0');
25 			cp++;
26 			continue;
27 		}
28 		if (base == 16 && isxdigit(c)) {
29 			val = (val << 4) + (c + 10 - (islower(c) ? 'a' : 'A'));
30 			cp++;
31 			continue;
32 		}
33 		break;
34 	}
35 	if (*cp == '.') {
36 		/*
37 		 * Internet format:
38 		 *	a.b.c.d
39 		 *	a.b.c	(with c treated as 16-bits)
40 		 *	a.b	(with b treated as 24 bits)
41 		 */
42 		if (pp >= parts + 4)
43 			return (-1);
44 		*pp++ = val, cp++;
45 		goto again;
46 	}
47 	if (*cp && !isspace(*cp))
48 		return (-1);
49 	n = pp - parts;
50 	if (n > 0) {
51 		if (n > 4)
52 			return (-1);
53 		*pp++ = val; n++;
54 		val = parts[0];
55 		if (n > 1)
56 			val <<= 24;
57 		if (n > 2)
58 			val |= (parts[1] & 0xff) << 16;
59 		if (n > 3)
60 			val |= (parts[2] & 0xff) << 8;
61 		if (n > 1)
62 			val |= parts[n - 1];
63 #if vax || pdp11
64 		val = htonl(val);
65 #endif
66 	}
67 	return (val);
68 }
69 
70