UNP chapter3 习题3.3

题目:试写一个名为inet_pton_loose的函数,它能处理如下情形:如果地址族为AF_INET且inet_pton返回0,那就调用inet_aton看是否成功;类似地,如果地址族为AF_INET6且inet_pton返回0,那么就调用inet_aton看是否成功,若成功返回其IPv4映射的IPv6地址。


写了个很蹩脚的代码验证一下,题目的意思应该是要验证inet_pton 和 inet_aton 对于输入参数的要求,改变输入的IPv4地址的格式来验证这两个函数的区别。但是最后提到IPv4映射的IPv6的地址有点不解,暂时先放个草稿在这里记录一下吧。


#include "unp.h"


in_addr_t inet_pton_loose(int family, const char *strptr,void *addrptr)
{
struct in_addr *ap = (struct in_addr *)addrptr;
int result = 0;

if((family == AF_INET) && (inet_pton(family,strptr,addrptr) == 0))
{
printf("the net protocol is IPv4 str is %s\n",strptr);
result = inet_aton(strptr,ap);
printf("result is %d\n",result);
if(result)
return ap->s_addr;
else 
return 0;
}
else if ((family == AF_INET6) && (inet_pton(family,strptr,addrptr) == 0))
{
printf("the net protocol is IPv6\n");
result = inet_aton(strptr,ap);
printf("result is %d\n",result);
if(result)
{
return ap->s_addr;
}
else 
return 0;
}

return 0;

}

int main (int argc, char **argv)
{
//if argv[1] is zero, means AF_INET type, 1 for AF_INET6 type
char s[20];
struct in_addr addr;
in_addr_t addr_result = 0;

if(argc < 2)
{
printf("usage: ./mytest \n");
return 1;
}
bzero(&addr,sizeof(struct in_addr));
memset(s,0,sizeof(s));
strcpy(s,argv[2]);

if(atoi(argv[1]) == 0)
{
printf("the net protocol is IPv4\n");

addr_result = inet_pton_loose(AF_INET,s,(void *)&addr);
printf("addr_result is %x\n",addr_result);
}
else if(atoi(argv[1]) == 1)
{
printf("the net protocol is IPv6\n");
addr_result = inet_pton_loose(AF_INET6,s,(void *)&addr);
printf("addr_result is %x\n",addr_result);


}

return 0;
}

你可能感兴趣的:(UNIX,网络编程)