网络: gethostbyname

 

gethostbyname 果然连接了网络, 根据域名获取了域名的正式名称, 别名和 ip 地址。

 

使用这个东西,首先要包含2个头文件:
#include <netdb.h>
#include <sys/socket.h>

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

struct hostent {
  char  *h_name;
  char  **h_aliases;
  int   h_addrtype;
  int   h_length;
  char  **h_addr_list;
  };
解释一下这个结构:
其中,
  char *h_name 表示的是主机的规范名。例如
www.google.com 的规范名其实是 www.l.google.com
  char   **h_aliases 表示的是主机的别名。
www.google.com 就是google他自己的别名。有的时候,有的主机可能有好几个别名,这些,其实都是为了易于用户记忆而为自己的网站多取的名字。
  int   h_addrtype 表示的是主机ip地址的类型,到底是ipv4(AF_INET),还是ipv6(AF_INET6)
  int   h_length 表示的是主机ip地址的长度
  int   **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。

 

下面是例程,有详细的注释。

 

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

int main(int argc, char ** argv)
{
	char *ptr, **pptr;
	struct hostent * hptr = NULL;
	char str[32];
	if (argc <= 1)
	{
		ptr = malloc(100);
		char *domain_google = "www.google.com";
		//set default domain name
		printf("size of domain name is: %d\n", strlen(domain_google));
		memcpy(ptr, domain_google, strlen(domain_google));
		ptr[strlen(domain_google)] = '\0';
		printf("size of default domain name is; %d\n", strlen(ptr)); 
	}
	else
	{
		ptr = argv[1];
	}

	if ((hptr = gethostbyname(ptr)) == NULL)
	{
		printf("gethostbyname error for host: %s\n", ptr);
		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;
			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;
	}
	return 0;
}
	

 

gcc -g gethostbyname.c -o gethostbyname
运行 ./gethostbyname 得到

size of domain name is: 14
size of default domain name is; 14
official hostname: www.l.google.com
 alias: www.google.com
 address: 74.125.71.106
 address: 74.125.71.105
 address: 74.125.71.99
 address: 74.125.71.104
 address: 74.125.71.103
 address: 74.125.71.147


 

你可能感兴趣的:(网络,struct,Google,null,domain,DST)