gethostbyname根据域名获取ip地址

gethostbyname函数根据域名解析出服务器的ip地址,它返回一个结构体struct hostent

struct hostent结构体

#include 

struct hostent {
	char * h_name; 		/ *主机的正式名称* /
	char ** h_aliases; 	/ *主机的别名,一个主机可以有多个别名* /
	int h_addrtype; 	/ *主机地址类型:IPV4-AF_INET* /
	int h_length; 		/ *主机地址字节长度,对于IPv4是四字节,即32* /
	char ** h_addr_list; / *地址列表* /
}
#define h_addr h_addr_list [0] / *用于向后兼容* /

示例:

//test_gethostbyname.c
#include 
#include 
#include 
#include 
#include 
#include 


int main(int argc, char **argv)
{
	char *hostname,**pptr;
	struct hostent *hptr;
	char str[32] = {0};


	hostname = argc < 2 ? "www.baidu.com" : argv[1];
	printf("hostname:%s\n", hostname);


	if((hptr = gethostbyname(hostname)) == NULL)
	{
		printf("gethostbyname(%s) error(%s)\n", hostname, strerror(errno));
		return 0;
	}

	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;
				
			//打印得到的而第一个地址
			printf("first address: %s\n", inet_ntop(hptr->h_addrtype, hptr->h_addr, str, sizeof(str)));
		
			for(; *pptr != NULL; pptr++)   //将得到的所有地址打印出来
			{
				//inet_ntop: 将网络字节序的二进制转换为文本字符串的格式
				printf("address: %s\n", inet_ntop(hptr->h_addrtype, *pptr, str, sizeof(str))); 
			}
			break;
		default:
			printf("unkown address type\n");
			break;
	}
	return 0;
}

参考资料
https://blog.csdn.net/wynter_/article/details/52529685
https://kenby.iteye.com/blog/1149534
https://blog.csdn.net/test1280/article/details/82949596

你可能感兴趣的:(C)