网络编程学习笔记(gethostbyname函数)

#include <netdb.h>
struct hostent* gethostbyname(const char* hostname);

成功,返回非空指针,出错返回空指针,同时设置h_errno

hostent结构体定义如下:

struct hostent
{
       char *h_name;// official name of host
       char **h_aliases;//pointer to array of pointers to alias names
       int h_addrtype;//host address type:AF_INET or AF_INET6
       int h_lenght;//length of address 4 or 6 
       char **h_addr_list;//ptr to array of ptrs with IPv4 or IPv6 addrs
};

gethostbyname与我们介绍的其他套接口函数的不同之处在于,当发生错误时,它不设置errno,而是将全局整数h_errno设置为定义在头文件<netdb.h>中的下列常数中的一个:

1、HOST_NOT_FOUND

2、TRY_AGAIN

3、NO_RECOVERY

4、NO_DATA

#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <unistd.h>


#define INET6_ADDRESTRLEN 48

int main(int argc, char **argv)
{
	char *ptr, **pptr;
	char str[INET6_ADDRESTRLEN];
	struct hostent* hptr;

	while (--argc > 0) {
		ptr = *++argv;
		if ((hptr = gethostbyname(ptr)) == NULL) {
			printf("gethostbyname error for host:%s:%s", 
				ptr, hstrerror(h_errno));
			continue;
		}
		printf("official hostname:%s\n", hptr->h_name);
		
		for (pptr = hptr->h_aliases; *pptr != NULL; pptr++) {
			printf("\tallas:%s\n", *pptr);
		}
	
		switch(hptr->h_addrtype) {
			case AF_INET:
				pptr = hptr->h_addr_list;
				for (; *pptr != NULL; pptr++) {
					printf("\taddress:%s\n",
					       inet_ntop(hptr->h_addrtype, *pptr, str, sizeof(str)));
			break;
			default:
				printf("unknown address type\n");
				break;
				}
		}
		
	}

	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

kgduu

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

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

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

打赏作者

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

抵扣说明:

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

余额充值