【Linux编程】gethostbyname 获取网站域名的IP地址解析

实现

【Linux编程】gethostbyname 获取网站域名的IP地址解析

代码:

#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
int main(int argc, char **argv)
{
	struct hostent *answer;
	int i;
	char ipstr[16];//为什么用16个字节?3*4+3+1=16,最多16个字节就是这样来的	
	if (argc != 2) 
	{
		printf("Usage: %s hostname
",argv[0]);
		exit(1);    
	}
	answer = gethostbyname(argv[1]);
	if (answer == NULL) 
	{
		herror("gethostbyname"); //由gethostbyname自带的错误处理函数
		exit(1);
	}
	for (i = 0; (answer->h_addr_list)[i] != NULL; i++) 
	{
		inet_ntop(AF_INET, (answer->h_addr_list)[i], ipstr, 16);
		printf("%s
", ipstr);
		printf("officail name : %s
", answer->h_name);
	}
	return 0;
}

原理浅析

gethostbyname()函数说明——用域名或主机名获取IP地址

包含头文件

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

函数原型

struct hostent *gethostbyname(const char *name);
这个函数的传入值是域名或者主机名,例如"www.baidu.com"等等。传出值,是一个hostent的结构。如果函数调用失败,将返回NULL。

返回hostent结构体类型指针

struct hostent
{
char *h_name;
char **h_aliases;
int h_addrtype;
int h_length;
char **h_addr_list;
#define h_addr h_addr_list[0]
};

hostent->h_name

表示的是主机的规范名。例如www.baidu.com的规范名其实是www.a.shifen.com。

hostent->h_aliases

表示的是主机的别名.www.baidu.com就是百度他自己的别名。有的时候,有的主机可能有好几个别名,这些,其实都是为了易于用户记忆而为自己的网站多取的名字。

hostent->h_addrtype

表示的是主机ip地址的类型,到底是ipv4(AF_INET),还是pv6(AF_INET6)

hostent->h_length

表示的是主机ip地址的长度

hostent->h_addr_lisst

表示的是主机的ip地址,注意,这个是以网络字节序存储的。千万不要直接用printf带%s参数来打这个东西,会有问题的哇。所以到真正需要打印出这个IP的话,需要调用inet_ntop()。

const char *inet_ntop(int af, const void *src, char *dst, socklen_t cnt) :

这个函数,是将类型为af的网络地址结构src,转换成主机序的字符串形式,存放在长度为cnt的字符串中。返回指向dst的一个指针。如果函数调用错误,返回值是NULL。