gethostbyname函数讲解

Gethostbyname:根据主机名或域名获取 官方域名、ip等信息。

原型:      

struct hostent *gethostbyname(const char *name);

 

struct hostent结构

struct hostent {
  char    *h_name;        /* official name of host */
  char    **h_aliases;    /* alias list */
  int     h_addrtype;     /* host address type */
  int     h_length;       /* length of address */
char    **h_addr_list;  /* list of addresses */
}

 

 struct hostent 结构图

 

 成功调用后返回如下图结构指针,否则返回NULL

代码如下:

#include <stdio.h>
#include <netdb.h>
#include <sys/socket.h>

#define IP_LEN 32

int main(int argc, char **argv)
{
	if(argc != 2)
	{
		printf("argument err!\n");
		return 0;
	} 

	char **ppcIp = NULL, **ppcAlias = NULL;
	char acOutIp[IP_LEN] = {0};
	struct hostent *pstHostent = NULL;
	int i = 0;

	if(NULL == (pstHostent = gethostbyname(argv[1])))
	{
		printf("Cannot resolve the hostname or domainname!\n");
		return 0;
	}
	printf("The official name is: %s\n", pstHostent->h_name);

	for(ppcAlias = pstHostent->h_aliases; *ppcAlias != NULL; ppcAlias++)
	{
		i++;
		printf("aliase %d: %s\n", i, *ppcAlias);
	}

	switch(pstHostent->h_addrtype)
	{
		case AF_INET:
		case AF_INET6:
			ppcIp = pstHostent->h_addr_list;
			for(i = 0; *ppcIp != NULL; ppcIp++)
			{
				i++;
				printf("IP %d: %s\n", i, inet_ntop(pstHostent->h_addrtype,
							 *ppcIp, acOutIp, sizeof(acOutIp)));
			}
			break;
		default:
			printf("unknown hostname type\n");
			break;
	}

	return 0;
}



实验结果:
 

[root@localhost test]# ./a.out www.google.com
The official name is: www.l.google.com
aliase 1: www.google.com
IP 1: 74.125.224.240
IP 2: 74.125.224.244
IP 3: 74.125.224.243
IP 4: 74.125.224.242
IP 5: 74.125.224.241


 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值