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 */
}
成功调用后返回如下图结构指针,否则返回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