您的位置:首页 > 其它

gethostbyname(),gethostbyaddr()的使用

2013-03-31 13:14 337 查看
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <stdlib.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <netinet/in.h>

int main(int argc, char **argv)
{
int i;
char str[32];
struct hostent * a;
struct in_addr inp;

if(inet_aton(argv[1],&inp))	a = gethostbyaddr (&inp,4, AF_INET);
else	a = gethostbyname (argv[1]);

printf("Official name of host is %s\n",(*a).h_name);
for(i=0;(*a).h_aliases[i];i++)
printf("Alias list is %s\n",(*a).h_aliases[i]);
printf("Host address type is %d\n",(*a).h_addrtype);
printf("Length of address is %d\n",(*a).h_length);
for(i=0;(*a).h_addr_list[i];i++)
printf("List of addresses from name server is %s\n",inet_ntop((*a).h_addrtype, (*a).h_addr_list[i], str,sizeof(str)));
return 0;
}

写了个网络编程的小程序,健壮性较差,但基本功能还算是实现了。说说调试过程中的一些问题吧。

1、开始时,我是把gethostbyname() gethostbyaddr()放在两个不同的函数中实现的,后来才用inet_aton()合并到一个函数中。

gethostbyname()参数比较简单,只要一个char*类型的URL就可以了。

相比之下,gethostbyaddr()的参数稍微复杂一点,一共需要三个参数,后两个参数比较简单。第一个参数函数原型中说是要const void*类型的,开始一直不知道要输入什么,通过在网上搜索相关的例子,查到了结果。说需要a pointer to a struct in_addr。这样疑问就解决了。

inet_ntop()实现32位二进制地址到点分十进制地址的转化(我是这么理解的)。参数也比较简单。

2、下面就是一个比较纠结的问题了。

刚开始合并到一起的时候运行总是提示段错误segmentation fault (core dumped)。

初次遇到这种错误真心是不知道怎么调试,无奈不会用gdb。

还好在stackoverflow上有热心网友解答了这个疑惑。

开始时是这样调用inet_aton的,乍一看似乎没什么问题,但细想就能发现问题了。

struct in_addr *hipaddr = NULL;
inet_aton(ptr,hipaddr);


inet_aton将转换后的地址存到hipaddr所指向的单元,初始化的时候hipaddr赋值为NULL,显然inet_aton是不能成功调用的。当hipaddr不赋值时,同样会出现这样的错误。

改成如上的程序会就会成功运行。

当然那个程序也需要完善。这里只是抛砖引玉。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: