关于Linux域下的域名解析函数gethostbyname()的使用
gethostbyname()原型:struct hostent* gethostbyname(const char *name);
调用函数成功返回一个hostent结构体
struct hostent
{
char *h_name;
char ** h_aliases;
short h_addrtype;
short h_length;
char ** h_addr_list;
};
测试代码
#include<stdio.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<stdlib.h>
#include<errno.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<signal.h>
#include<unistd.h>
#include<netdb.h>
#include<string.h>
#include <arpa/inet.h>
int main(int argc,char *argv[])
{
int optret;
char *ipname = NULL;
char ip[50];
struct hostent *gethost = NULL;
int file_fd;
char buf[50];
char *ptrf;
char *ptrb;
int n;
char fptr[50];
const char *ptr = NULL;
struct in_addr inAddr;
while((optret = getopt(argc,argv,"i:")) != -1)
{
switch(optret)
{
case 'i':
ipname = optarg;
printf("option = i,the ipname is:%s\n",optarg);
break;
}
}
gethost = gethostbyname(ipname);
if (NULL == gethost)
{
perror("get ipaddr fail!");
return -1;
}
printf("get host successfully!\n");
memset(ip,0,sizeof(ip));
ptr = inet_ntop(gethost->h_addrtype,gethost->h_addr_list[0],ip,sizeof(ip));
printf("DNS ip is:%s\n",ptr);
/////////////////////////////调用ping命令获取IP(文件IO)////////////////////////////////////
system("ping studio.iot-yun.com -c 2 >> /home/deepin/APUE/malunkun/test/.domain.log");
file_fd=open("/home/deepin/APUE/malunkun/test/.domain.log",O_RDONLY,644);
if (file_fd < 0)
{
perror("open file fail!\n");
}
read(file_fd,buf,sizeof(buf));
close(file_fd);
ptrf = strstr(buf,"(");
ptrf += 1;
ptrb = strstr(buf,")");
n = strlen(ptrf)-strlen(ptrb);
strncpy(fptr,ptrf,n);
printf("ping ip is:%s\n",fptr);
//////////////////////////////////////////////////////////////////////////
return 0;
}
运行结果
这里得到的IP并不一样;后来分析应该是百度有多个IP的原因;
用两个IP分别进行网页登录:
发现都能正常登录百度,解析算是成功了!