1、问题
开发过程中,发现dhcp失败后gethostbyname函数一直失败
连接上网络后,也一直调用失败
2、原因
调用gethostbyname失败后的变量存储在h_errno中,所以不能用perror打印,
需要使用herror打印,错误为Host name lookup failure。
3、解决
在调用gethostbyname之前,先调用res_init函数
4、res_init
函数原型:
int res_init(void);
头文件:
#include <resolv.h>
作用:
res_init函数用于读取配置文件并修改环境变量:LOCALDOMAIN。
在调用其他地址解析函数前通常要先调用res_init,如果执行成功, 函数返回0,否则返回-1。
5、例程
int my_gethostbyname(char* hostname)
{
char msg[64];
struct hostent* ent;
int ret = inet_addr(hostname);
if(ret && (ret != -1))
{
return ret;
}
ret = res_init();
if (ret < 0)
{
fprintf(stderr, "================ res_init failed ==================\n");
return -1;
}
if((ent = gethostbyname(hostname)) != NULL)
{
inet_ntop(ent->h_addrtype, ent->h_addr, msg, sizeof(msg));
return inet_addr((char*)msg);
}
else
{
herror("gethostbyname fail");
}
return -1;
}
在开发中遇到dhcp失败导致gethostbyname函数持续失败的问题,即使网络恢复也无效。解决方法是在调用gethostbyname之前,先调用res_init函数初始化资源。res_init函数读取配置文件并更新环境变量LOCALDOMAIN。当gethostbyname仍然失败时,通过herror打印错误信息显示为Hostnamelookup failure。提供了一个包含res_init调用的my_gethostbyname函数示例。
5213

被折叠的 条评论
为什么被折叠?



