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