1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18: #if defined(LIBC_SCCS) && !defined(lint)
19: static const char rcsid[] = "$BINDId: inet_net_ntop.c,v 1.6 1999/01/08 19:23:42 vixie Exp $";
20: #endif
21:
22: #include <sys/types.h>
23: #include <sys/socket.h>
24: #include <netinet/in.h>
25: #include <arpa/inet.h>
26:
27: #include <errno.h>
28: #include <stdio.h>
29: #include <string.h>
30: #include <stdlib.h>
31:
32: #ifdef SPRINTF_CHAR
33: # define SPRINTF(x) strlen(sprintfx)
34: #else
35: # define SPRINTF(x) ((size_t)sprintf x)
36: #endif
37:
38: static char * inet_net_ntop_ipv4 (const u_char *src, int bits,
39: char *dst, size_t size) __THROW;
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51: char *
52: inet_net_ntop(af, src, bits, dst, size)
53: int af;
54: const void *src;
55: int bits;
56: char *dst;
57: size_t size;
58: {
59: switch (af) {
60: case AF_INET:
61: return (inet_net_ntop_ipv4(src, bits, dst, size));
62: default:
63: __set_errno (EAFNOSUPPORT);
64: return (NULL);
65: }
66: }
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81: static char *
82: inet_net_ntop_ipv4(src, bits, dst, size)
83: const u_char *src;
84: int bits;
85: char *dst;
86: size_t size;
87: {
88: char *odst = dst;
89: char *t;
90: u_int m;
91: int b;
92:
93: if (bits < 0 || bits > 32) {
94: __set_errno (EINVAL);
95: return (NULL);
96: }
97: if (bits == 0) {
98: if (size < sizeof "0")
99: goto emsgsize;
100: *dst++ = '0';
101: size--;
102: *dst = '\0';
103: }
104:
105:
106: for (b = bits / 8; b > 0; b--) {
107: if (size < sizeof "255.")
108: goto emsgsize;
109: t = dst;
110: dst += SPRINTF((dst, "%u", *src++));
111: if (b > 1) {
112: *dst++ = '.';
113: *dst = '\0';
114: }
115: size -= (size_t)(dst - t);
116: }
117:
118:
119: b = bits % 8;
120: if (b > 0) {
121: if (size < sizeof ".255")
122: goto emsgsize;
123: t = dst;
124: if (dst != odst)
125: *dst++ = '.';
126: m = ((1 << b) - 1) << (8 - b);
127: dst += SPRINTF((dst, "%u", *src & m));
128: size -= (size_t)(dst - t);
129: }
130:
131:
132: if (size < sizeof "/32")
133: goto emsgsize;
134: dst += SPRINTF((dst, "/%u", bits));
135: return (odst);
136:
137: emsgsize:
138: __set_errno (EMSGSIZE);
139: return (NULL);
140: }