网络编程:gethostbyname()测试程序

/******************************************************************************************************************
参考:http://blog.csdn.net/leesphone/article/details/2138775
说明:gethostbyname()测试程序。
******************************************************************************************************************/ 

#include <netdb.h>
#include <sys/socket.h>
#include <stdio.h>
int main(int argc, char **argv)
{
	char *ptr,**pptr;
	struct hostent *hptr;
	char str[32];
	/* 取得命令后第一个参数,即要解析的域名或主机名 */
	ptr = argv[1];
	/* 调用gethostbyname()。调用结果都存在hptr中 */
	if((hptr = gethostbyname(ptr)) == NULL )
	{
		printf("gethostbyname error for host:%s\n", ptr);
		return 0; /* 如果调用gethostbyname发生错误,返回1 */
	}
	/* 将主机的规范名打出来 */
	printf("official hostname:%s\n",hptr->h_name);
	/* 主机可能有多个别名,将所有别名分别打出来 */
	for(pptr = hptr->h_aliases; *pptr != NULL; pptr++)
		printf(" alias:%s\n",*pptr);
	/* 根据地址类型,将地址打出来 */
	switch(hptr->h_addrtype)
	{
		case AF_INET:
		case AF_INET6:
		pptr=hptr->h_addr_list;
		/* 将刚才得到的所有地址都打出来。其中调用了inet_ntop()函数 */
		for(;*pptr!=NULL;pptr++)
			printf(" address:%s\n", inet_ntop(hptr->h_addrtype, *pptr, str, sizeof(str)));
		break;
		default:
		printf("unknown address type\n");
		break;
	}
	printf(" h_length:%ld\n", hptr->h_length);
	return 0;
}

运行结果:

[root@localhost gcc]# ./a.out www.baidu.com
official hostname:www.a.shifen.com
 alias:www.baidu.com
 address:61.135.169.125
 address:61.135.169.105
 h_length:4
[root@localhost gcc]# 
测试时还冒昧将inet_ntop换成inet_ntoa,可知入参类型都不一样,inet_ntoa的型参为in_addr结构体,而inet_ntop的是hostent这样一个结构体。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

袁保康

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值