gethostbyname(),gethostbyaddr()的使用

#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不赋值时,同样会出现这样的错误。

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

当然那个程序也需要完善。这里只是抛砖引玉。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值