对端IP地址可能会改变,想通过dns方式来获取对端IP地址。即在本地文件中配置对端网址,通过该网址获取到IP。我写了如下代码,ping www.baidu.com有回复报文,但是程序却得到IP地址,还需要什么配置吗?请高手指导下,谢谢!
int main(int argc, char **argv)
{
char **pptr = NULL;
struct hostent *hptr = NULL;
char str[32] = {0};
char *dns_data = NULL;
char *filename = "/home/qshy/dns_test.c";
//读取配置文件数据(即对端网址)
if (-1 == read_dns(filename, &dns_data))
{
printf("read_dns failed.\n");
return -1;
}
if((hptr = gethostbyname(dns_data)) == NULL)
{
printf(" gethostbyname error for host:%s\n", dns_data);
printf("error:%s\n", strerror(errno));
free(dns_data);
return 0;
}
free(dns_data);
//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)));
//printf(" first address: %s\n",
// inet_ntop(hptr->h_addrtype, hptr->h_addr, str, sizeof(str)));
break;
default:
printf("unknown address type\n");
break;
}
free(dns_data);
return 0;
}