C咖咖 2015-06-10 08:12 采纳率: 0%
浏览 2110

centos上通过dns方式调用gethostbyname函数获取IP地址,还需要哪些设置吗?

对端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;

}

  • 写回答

1条回答

  • oyljerry 2015-06-10 14:54
    关注

    是没有获取到ip地址吧?可以查看一下错误信息,是不是网络问题或者防火墙

    评论

报告相同问题?

悬赏问题

  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿