1 /*
2 * Copyright (c) 1983, 1990, 1993
3 * The Regents of the University of California. All rights reserved.
4 *
5 * %sccs.include.redist.c%
6 */
7
8 #if defined(LIBC_SCCS) && !defined(lint)
9 static char sccsid[] = "@(#)inet_addr.c 8.1 (Berkeley) 06/17/93";
10 #endif /* LIBC_SCCS and not lint */
11
12 #include <sys/param.h>
13 #include <netinet/in.h>
14 #include <arpa/inet.h>
15 #include <ctype.h>
16
17 /*
18 * Ascii internet address interpretation routine.
19 * The value returned is in network order.
20 */
21 u_long
inet_addr(cp)22 inet_addr(cp)
23 register const char *cp;
24 {
25 struct in_addr val;
26
27 if (inet_aton(cp, &val))
28 return (val.s_addr);
29 return (INADDR_NONE);
30 }
31
32 /*
33 * Check whether "cp" is a valid ascii representation
34 * of an Internet address and convert to a binary address.
35 * Returns 1 if the address is valid, 0 if not.
36 * This replaces inet_addr, the return value from which
37 * cannot distinguish between failure and a local broadcast address.
38 */
39 int
inet_aton(cp,addr)40 inet_aton(cp, addr)
41 register const char *cp;
42 struct in_addr *addr;
43 {
44 register u_long val;
45 register int base, n;
46 register char c;
47 u_int parts[4];
48 register u_int *pp = parts;
49
50 for (;;) {
51 /*
52 * Collect number up to ``.''.
53 * Values are specified as for C:
54 * 0x=hex, 0=octal, other=decimal.
55 */
56 val = 0; base = 10;
57 if (*cp == '0') {
58 if (*++cp == 'x' || *cp == 'X')
59 base = 16, cp++;
60 else
61 base = 8;
62 }
63 while ((c = *cp) != '\0') {
64 if (isascii(c) && isdigit(c)) {
65 val = (val * base) + (c - '0');
66 cp++;
67 continue;
68 }
69 if (base == 16 && isascii(c) && isxdigit(c)) {
70 val = (val << 4) +
71 (c + 10 - (islower(c) ? 'a' : 'A'));
72 cp++;
73 continue;
74 }
75 break;
76 }
77 if (*cp == '.') {
78 /*
79 * Internet format:
80 * a.b.c.d
81 * a.b.c (with c treated as 16-bits)
82 * a.b (with b treated as 24 bits)
83 */
84 if (pp >= parts + 3 || val > 0xff)
85 return (0);
86 *pp++ = val, cp++;
87 } else
88 break;
89 }
90 /*
91 * Check for trailing characters.
92 */
93 if (*cp && (!isascii(*cp) || !isspace(*cp)))
94 return (0);
95 /*
96 * Concoct the address according to
97 * the number of parts specified.
98 */
99 n = pp - parts + 1;
100 switch (n) {
101
102 case 1: /* a -- 32 bits */
103 break;
104
105 case 2: /* a.b -- 8.24 bits */
106 if (val > 0xffffff)
107 return (0);
108 val |= parts[0] << 24;
109 break;
110
111 case 3: /* a.b.c -- 8.8.16 bits */
112 if (val > 0xffff)
113 return (0);
114 val |= (parts[0] << 24) | (parts[1] << 16);
115 break;
116
117 case 4: /* a.b.c.d -- 8.8.8.8 bits */
118 if (val > 0xff)
119 return (0);
120 val |= (parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8);
121 break;
122 }
123 if (addr)
124 addr->s_addr = htonl(val);
125 return (1);
126 }
127