Libinfo-129.tar.gz
[apple/libinfo.git] / gen.subproj / inet_ntop.c
1
2 #include <sys/types.h>
3 #include <netinet/in.h>
4 #include <stdio.h>
5 #include <string.h>
6 #include <sys/socket.h>
7
8 void __res_close()
9 {
10 }
11
12 const char *inet_ntop6(const struct in6_addr *addr,char *buf,size_t len)
13 {
14 const u_int16_t *ap=addr->__u6_addr.__u6_addr16;
15 int colon=2;
16 int i;
17 char *bp=buf;
18
19 for(i=0;i<8;i++,ap++)
20 {
21 if(bp>=buf+len-1)
22 {
23 buf[len-1]=0;
24 return buf;
25 }
26 if(*ap || colon==-1)
27 {
28 if(colon==2)
29 colon=0;
30 if(colon)
31 colon=-1;
32 sprintf(bp,"%x",*ap);
33 bp+=strlen(bp);
34 if(i!=7)
35 *bp++=':';
36 }
37 else
38 {
39 if(colon==2)
40 {
41 *bp++=':';
42 *bp++=':';
43 }
44 else if(!colon && i!=7)
45 *bp++=':';
46 colon=1;
47 }
48 }
49 *bp=0;
50 return buf;
51 }
52
53 const char *inet_ntop4(const struct in_addr *addr,char *buf,size_t len)
54 {
55 const u_int8_t *ap=(u_int8_t*)&addr->s_addr;
56 int i;
57 char *bp=buf;
58
59 for(i=0;i<4;i++,ap++)
60 {
61 if(bp>=buf+len-1)
62 {
63 buf[len-1]=0;
64 return buf;
65 }
66 sprintf(bp,"%d",*ap);
67 bp+=strlen(bp);
68 if(i!=3)
69 *bp++='.';
70 }
71 *bp=0;
72 return buf;
73 }
74
75 const char *inet_ntop(int af,const void *addr,char *buf,size_t len)
76 {
77 if(af==AF_INET6)
78 return inet_ntop6(addr,buf,len);
79 if(af==AF_INET)
80 return inet_ntop4(addr,buf,len);
81 return NULL;
82 }