函数原型:
- gethostbyname函数是通过主机名称获取主机的完整信息。name参数是目标主机的主机 名称。
- gethostbyaddr函数是通过IP地址获取主机的完整信息。addr是网络字节序的IP地址,len参数是IP地址的长度,type参数是IP地址的类型(合法类型包括AF_INET,AF_INET6)
- 两个函数的返回都是hostent结构体类型指针。hostent结构体定义如下:
代码实现:
- gethostbyname()
#include<stdio.h>
#include<netdb.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
#include<arpa/inet.h>
int main(int argc, char * argv[])
{
char **p1;
char **p2;
struct hostent *host;
char hostname[60];
int ret = 0;
int i=0;
char str[30];
ret = gethostname(hostname,sizeof(hostname));
printf("the hostname:%s\n",hostname);
hostname[strlen(hostname)+1] = '\0';
/*利用主机名称获取完整的主机信息*/
host = gethostbyname(hostname);
printf("the hostname after getosbyname: %s \n",host->h_name);
/*主机别名列表*/
printf("the other name of host:\n");
for(p1=host->h_aliases; *p1!=NULL; p1++)
{
i++;
printf("NO.%d:%s\n",i,p1[0]);
}
if(i==0)
{
printf("none\n");
}
i = 0;
printf("the type of address:%d\n",host->h_addrtype);
printf("the length of the address:%d\n",host->h_length);
/*按照网络字节序列出的主机ip地址表*/
printf("the IP of host:\n");
switch(host->h_addrtype)
{
case AF_INET://ipv4
case AF_INET6:
{
p2 = host->h_addr_list;
while(*p2!=NULL)
{
printf("address:%s\n",inet_ntop(host->h_addrtype, *p2, str, sizeof(str) ));
p2++;
}
break;
}
default:
{
printf("none type of address\n");
break;
}
}
return 0;
}
2.gethostbyaddr()
#include<stdio.h>
#include<netdb.h>
#include<stdlib.h>
#include<arpa/inet.h>
#include<string.h>
int main(int argc, char *argv[])
{
if(argc<2)
{
printf("the argc need more two\n");
return 1;
}
struct hostent *host;
const char *add = argv[1];
char p[30];
inet_pton(AF_INET, add, p);
host = gethostbyaddr(p, strlen(p), AF_INET);
printf("hostname:%s\n",host->h_name);
return 0;
}
运行结果: