BSD 4_3 release
[unix-history] / usr / src / lib / libc / inet / inet_addr.c
CommitLineData
bb0cfa24
DF
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
2ce81398 7#if defined(LIBC_SCCS) && !defined(lint)
95f51977 8static char sccsid[] = "@(#)inet_addr.c 5.2 (Berkeley) 3/9/86";
2ce81398 9#endif LIBC_SCCS and not lint
5e649950
SL
10
11#include <sys/types.h>
12#include <ctype.h>
056d5bbd 13#include <netinet/in.h>
5e649950 14
ff79189c
SL
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.
d6c70669 20 * The value returned is in network order.
ff79189c 21 */
b2053919 22u_long
ff79189c
SL
23inet_addr(cp)
24 register char *cp;
25{
d6c70669 26 register u_long val, base, n;
ff79189c 27 register char c;
d6c70669 28 u_long parts[4], *pp = parts;
ff79189c
SL
29
30again:
d6c70669
SL
31 /*
32 * Collect number up to ``.''.
33 * Values are specified as for C:
34 * 0x=hex, 0=octal, other=decimal.
35 */
ff79189c
SL
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 }
d6c70669
SL
66 /*
67 * Check for trailing characters.
68 */
ff79189c
SL
69 if (*cp && !isspace(*cp))
70 return (-1);
d6c70669
SL
71 *pp++ = val;
72 /*
73 * Concoct the address according to
74 * the number of parts specified.
75 */
ff79189c 76 n = pp - parts;
d6c70669
SL
77 switch (n) {
78
79 case 1: /* a -- 32 bits */
ff79189c 80 val = parts[0];
d6c70669
SL
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);
ff79189c 99 }
d6c70669 100 val = htonl(val);
ff79189c
SL
101 return (val);
102}