]>
git.saurik.com Git - apple/libinfo.git/blob - gen.subproj/inet_ntop.c
3 #include <netinet/in.h>
9 #include <sys/socket.h>
15 #define MAX_V4_ADDR_LEN 16
16 #define MAX_V6_ADDR_LEN 64
18 static const char *hexchars
= "0123456789abcdef";
21 inet_ntop6(const struct in6_addr
*addr
, char *dst
, socklen_t size
)
23 char hexa
[8][5], tmp
[MAX_V6_ADDR_LEN
];
26 int32_t i
, j
, k
, skip
;
43 memset(tmp
, 0, MAX_V6_ADDR_LEN
);
45 /* check for mapped or compat addresses */
46 i
= IN6_IS_ADDR_V4MAPPED(addr
);
47 j
= IN6_IS_ADDR_V4COMPAT(addr
);
48 if ((i
!= 0) || (j
!= 0))
50 a4
.s_addr
= addr
->__u6_addr
.__u6_addr32
[3];
51 sprintf(tmp
, "::%s%s", (i
!= 0) ? "ffff:" : "", inet_ntoa(a4
));
52 len
= strlen(tmp
) + 1;
59 memcpy(dst
, tmp
, len
);
64 for (i
= 0; i
< 16; i
+= 2)
69 memset(hexa
[k
], 0, 5);
71 x8
= addr
->__u6_addr
.__u6_addr8
[i
];
77 hexa
[k
][j
++] = hexchars
[hx8
];
81 if ((skip
== 0) || ((skip
== 1) && (hx8
!= 0)))
84 hexa
[k
][j
++] = hexchars
[hx8
];
87 x8
= addr
->__u6_addr
.__u6_addr8
[i
+ 1];
90 if ((skip
== 0) || ((skip
== 1) && (hx8
!= 0)))
92 hexa
[k
][j
++] = hexchars
[hx8
];
96 hexa
[k
][j
++] = hexchars
[hx8
];
101 /* find runs of zeros for :: convention */
103 for (i
= 7; i
>= 0; i
--)
106 x16
= addr
->__u6_addr
.__u6_addr16
[i
];
112 /* find longest run of zeros */
115 for(i
= 0; i
< 8; i
++)
124 for(i
= 0; i
< 8; i
++)
126 if (i
!= k
) zr
[i
] = 0;
130 for (i
= 0; i
< 8; i
++)
134 /* check for leading zero */
135 if (i
== 0) tmp
[len
++] = ':';
140 for (j
= 0; hexa
[i
][j
] != '\0'; j
++) tmp
[len
++] = hexa
[i
][j
];
141 if (i
!= 7) tmp
[len
++] = ':';
153 memcpy(dst
, tmp
, len
);
158 inet_ntop4(const struct in_addr
*addr
, char *dst
, socklen_t size
)
160 char tmp
[MAX_V4_ADDR_LEN
], *p
;
161 const u_int8_t
*ap
= (u_int8_t
*)&addr
->s_addr
;
166 errno
= EAFNOSUPPORT
;
176 memset(tmp
, 0, MAX_V4_ADDR_LEN
);
178 /* 3 dots, trailing nul */
183 for (i
= 0; i
< 4; i
++, ap
++)
185 snprintf(p
, 4, "%d", *ap
);
189 if (i
< 3) *p
++ = '.';
198 memcpy(dst
, tmp
, len
);
203 inet_ntop(int af
, const void *addr
, char *buf
, socklen_t len
)
205 if (af
== AF_INET6
) return inet_ntop6(addr
, buf
, len
);
206 if (af
== AF_INET
) return inet_ntop4(addr
, buf
, len
);
208 errno
= EAFNOSUPPORT
;