xref: /csrg-svn/lib/libc/net/inet_addr.c (revision 26612)
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.2 (Berkeley) 03/09/86";
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 		base = 8, cp++;
39 	if (*cp == 'x' || *cp == 'X')
40 		base = 16, cp++;
41 	while (c = *cp) {
42 		if (isdigit(c)) {
43 			val = (val * base) + (c - '0');
44 			cp++;
45 			continue;
46 		}
47 		if (base == 16 && isxdigit(c)) {
48 			val = (val << 4) + (c + 10 - (islower(c) ? 'a' : 'A'));
49 			cp++;
50 			continue;
51 		}
52 		break;
53 	}
54 	if (*cp == '.') {
55 		/*
56 		 * Internet format:
57 		 *	a.b.c.d
58 		 *	a.b.c	(with c treated as 16-bits)
59 		 *	a.b	(with b treated as 24 bits)
60 		 */
61 		if (pp >= parts + 4)
62 			return (-1);
63 		*pp++ = val, cp++;
64 		goto again;
65 	}
66 	/*
67 	 * Check for trailing characters.
68 	 */
69 	if (*cp && !isspace(*cp))
70 		return (-1);
71 	*pp++ = val;
72 	/*
73 	 * Concoct the address according to
74 	 * the number of parts specified.
75 	 */
76 	n = pp - parts;
77 	switch (n) {
78 
79 	case 1:				/* a -- 32 bits */
80 		val = parts[0];
81 		break;
82 
83 	case 2:				/* a.b -- 8.24 bits */
84 		val = (parts[0] << 24) | (parts[1] & 0xffffff);
85 		break;
86 
87 	case 3:				/* a.b.c -- 8.8.16 bits */
88 		val = (parts[0] << 24) | ((parts[1] & 0xff) << 16) |
89 			(parts[2] & 0xffff);
90 		break;
91 
92 	case 4:				/* a.b.c.d -- 8.8.8.8 bits */
93 		val = (parts[0] << 24) | ((parts[1] & 0xff) << 16) |
94 		      ((parts[2] & 0xff) << 8) | (parts[3] & 0xff);
95 		break;
96 
97 	default:
98 		return (-1);
99 	}
100 	val = htonl(val);
101 	return (val);
102 }
103