]>
git.saurik.com Git - apple/libc.git/blob - net/inet_ntop.c
3 #include <netinet/in.h>
9 #include <sys/socket.h>
11 #define MAX_V4_ADDR_LEN 16
12 #define MAX_V6_ADDR_LEN 64
14 static const char *hexchars
= "0123456789abcdef";
17 inet_ntop6(const struct in6_addr
*addr
, char *dst
, socklen_t size
)
19 char hexa
[8][5], tmp
[MAX_V6_ADDR_LEN
];
22 int32_t i
, j
, k
, skip
;
39 memset(tmp
, 0, MAX_V6_ADDR_LEN
);
41 /* check for mapped or compat addresses */
42 i
= IN6_IS_ADDR_V4MAPPED(addr
);
43 j
= IN6_IS_ADDR_V4COMPAT(addr
);
44 if ((i
!= 0) || (j
!= 0))
46 a4
.s_addr
= addr
->__u6_addr
.__u6_addr32
[3];
47 sprintf(tmp
, "::%s%s", (i
!= 0) ? "ffff:" : "", inet_ntoa(a4
));
48 len
= strlen(tmp
) + 1;
55 memcpy(dst
, tmp
, len
);
60 for (i
= 0; i
< 16; i
+= 2)
65 memset(hexa
[k
], 0, 5);
67 x8
= addr
->__u6_addr
.__u6_addr8
[i
];
73 hexa
[k
][j
++] = hexchars
[hx8
];
77 if ((skip
== 0) || ((skip
== 1) && (hx8
!= 0)))
80 hexa
[k
][j
++] = hexchars
[hx8
];
83 x8
= addr
->__u6_addr
.__u6_addr8
[i
+ 1];
86 if ((skip
== 0) || ((skip
== 1) && (hx8
!= 0)))
88 hexa
[k
][j
++] = hexchars
[hx8
];
92 hexa
[k
][j
++] = hexchars
[hx8
];
97 /* find runs of zeros for :: convention */
99 for (i
= 7; i
>= 0; i
--)
102 x16
= addr
->__u6_addr
.__u6_addr16
[i
];
108 /* find longest run of zeros */
111 for(i
= 0; i
< 8; i
++)
120 for(i
= 0; i
< 8; i
++)
122 if (i
!= k
) zr
[i
] = 0;
126 for (i
= 0; i
< 8; i
++)
130 /* check for leading zero */
131 if (i
== 0) tmp
[len
++] = ':';
136 for (j
= 0; hexa
[i
][j
] != '\0'; j
++) tmp
[len
++] = hexa
[i
][j
];
137 if (i
!= 7) tmp
[len
++] = ':';
149 memcpy(dst
, tmp
, len
);
154 inet_ntop4(const struct in_addr
*addr
, char *dst
, socklen_t size
)
156 char tmp
[MAX_V4_ADDR_LEN
], *p
;
157 const u_int8_t
*ap
= (u_int8_t
*)&addr
->s_addr
;
162 errno
= EAFNOSUPPORT
;
172 memset(tmp
, 0, MAX_V4_ADDR_LEN
);
174 /* 3 dots, trailing nul */
179 for (i
= 0; i
< 4; i
++, ap
++)
181 snprintf(p
, 4, "%d", *ap
);
185 if (i
< 3) *p
++ = '.';
194 memcpy(dst
, tmp
, len
);
199 inet_ntop(int af
, const void *addr
, char *buf
, socklen_t len
)
201 if (af
== AF_INET6
) return inet_ntop6(addr
, buf
, len
);
202 if (af
== AF_INET
) return inet_ntop4(addr
, buf
, len
);
204 errno
= EAFNOSUPPORT
;