xref: /titanic_51/usr/src/lib/libbc/libc/inet/inet_network.c (revision a1249923836cbb3352aed4d6001582ef89cb302c)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 	 /* from UCB 4.2 82/10/07 */
29 
30 #include <sys/types.h>
31 #include <ctype.h>
32 
33 /*
34  * Internet network address interpretation routine.
35  * The library routines call this routine to interpret
36  * network numbers.
37  */
38 u_long
39 inet_network(cp)
40 	register char *cp;
41 {
42 	register u_long val, base, n;
43 	register char c;
44 	u_long parts[4], *pp = parts;
45 	register int i;
46 
47 again:
48 	val = 0; base = 10;
49 	if (*cp == '0') {
50 		if (*++cp == 'x' || *cp == 'X')
51 			base = 16, cp++;
52 		else
53 			base = 8;
54 	}
55 	while ((c = *cp) != '\0') {
56 		if (isdigit(c)) {
57 			if ((c - '0') >= base)
58 			    break;
59 			val = (val * base) + (c - '0');
60 			cp++;
61 			continue;
62 		}
63 		if (base == 16 && isxdigit(c)) {
64 			val = (val << 4) + (c + 10 - (islower(c) ? 'a' : 'A'));
65 			cp++;
66 			continue;
67 		}
68 		break;
69 	}
70 	if (pp >= parts + 4 || val > 0xff)
71 		return (-1);
72 	*pp++ = val;
73 	if (*cp == '.') {
74 		cp++;
75 		goto again;
76 	}
77 	if (*cp != '\0' && !isspace(*cp))
78 		return (-1);
79 	n = pp - parts;
80 	for (val = 0, i = 0; i < n; i++) {
81 		val <<= 8;
82 		val |= parts[i];
83 	}
84 	return (val);
85 }
86