当前位置: 技术问答>linux和unix
Linux下地址转换函数的问题,在IPv4下和IPv6下现象不同?
来源: 互联网 发布时间:2015-11-23
本文导语: 程序如下: #include #include #include #include #include int main() { unsigned int a,b,c; char *p1="2006::121"; b=inet_pton(AF_INET6,p1,&a); c=a; printf("a=%d b=%d c=%dn",a,b,c); char p2[64],p3[64]...
程序如下:
#include
#include
#include
#include
#include
int main()
{
unsigned int a,b,c;
char *p1="2006::121";
b=inet_pton(AF_INET6,p1,&a);
c=a;
printf("a=%d b=%d c=%dn",a,b,c);
char p2[64],p3[64];
bzero(p2,sizeof(p2));
bzero(p3,sizeof(p3));
inet_ntop(AF_INET6,&a,p2,sizeof(p2));
inet_ntop(AF_INET6,&c,p3,sizeof(p3));
printf("p2=%s length is %dn",p2,strlen(p2));
printf("p3=%s length is %dn",p3,strlen(p3));
}
--------------------------------------
该程序就是想先由字符串 "2006::121"通过地址转换函数,转到网络二进制形式,然后在利用相反的函数转换回来,
设置了2个变量a和c,a可以顺利的实现互相转换,可以c就不能实现了,不知道是为什么?
运行结果如下:
a=1568 b=1 c=1568
p2=2006::121 length is 9
p3=2006:0:100:0:2006:: length is 19
#include
#include
#include
#include
#include
int main()
{
unsigned int a,b,c;
char *p1="2006::121";
b=inet_pton(AF_INET6,p1,&a);
c=a;
printf("a=%d b=%d c=%dn",a,b,c);
char p2[64],p3[64];
bzero(p2,sizeof(p2));
bzero(p3,sizeof(p3));
inet_ntop(AF_INET6,&a,p2,sizeof(p2));
inet_ntop(AF_INET6,&c,p3,sizeof(p3));
printf("p2=%s length is %dn",p2,strlen(p2));
printf("p3=%s length is %dn",p3,strlen(p3));
}
--------------------------------------
该程序就是想先由字符串 "2006::121"通过地址转换函数,转到网络二进制形式,然后在利用相反的函数转换回来,
设置了2个变量a和c,a可以顺利的实现互相转换,可以c就不能实现了,不知道是为什么?
运行结果如下:
a=1568 b=1 c=1568
p2=2006::121 length is 9
p3=2006:0:100:0:2006:: length is 19
|
晕,你man一下inet_pton,看看用法,好不?程序应该是这样的:
#include
#include
#include
#include
#include
int main()
{
struct in6_addr a,c;
unsigned int b;
char *p1="2006::121";
b=inet_pton(AF_INET6,p1,&a);
c=a;
// printf("a=%d b=%d c=%dn",a,b,c);
char p2[64],p3[64];
bzero(p2,sizeof(p2));
bzero(p3,sizeof(p3));
inet_ntop(AF_INET6,&a,p2,sizeof(p2));
inet_ntop(AF_INET6,&c,p3,sizeof(p3));
printf("p2=%s length is %dn",p2,strlen(p2));
printf("p3=%s length is %dn",p3,strlen(p3));
}
执行结果是:
$ ./a.out
p2=2006::121 length is 9
p3=2006::121 length is 9
#include
#include
#include
#include
#include
int main()
{
struct in6_addr a,c;
unsigned int b;
char *p1="2006::121";
b=inet_pton(AF_INET6,p1,&a);
c=a;
// printf("a=%d b=%d c=%dn",a,b,c);
char p2[64],p3[64];
bzero(p2,sizeof(p2));
bzero(p3,sizeof(p3));
inet_ntop(AF_INET6,&a,p2,sizeof(p2));
inet_ntop(AF_INET6,&c,p3,sizeof(p3));
printf("p2=%s length is %dn",p2,strlen(p2));
printf("p3=%s length is %dn",p3,strlen(p3));
}
执行结果是:
$ ./a.out
p2=2006::121 length is 9
p3=2006::121 length is 9