您的位置:首页 > 理论基础 > 计算机网络

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

2013-01-18 17:56 169 查看
/******************************************************************************************************************

参考: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这样一个结构体。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: