gethostbyaddr_r && gethostbyname_r
一、定义
以下定义来自chatGPT :
gethostbyaddr_r
和gethostbyname_r
都是用于获取主机名的函数,但是它们分别针对不同的网络地址类型。
gethostbyaddr_r
用于通过 IP 地址获取对应的主机名,接受一个 IPv4 或 IPv6 地址作为参数。
gethostbyname_r
则是通过主机名获取对应的 IP 地址,接受一个主机名作为参数。
二、问题记录
在测试时发现代码中有使用gethostbyaddr_r 和 gethostbyname_r来解析域名,单独把该IP和端口拿出来测试,发现该IP在调用gethostbyaddr_r
时耗时4秒 。而在使用gethostbyname_r
的时候很快。
三、解决
切换到 root
用户,vim
打开 etc/hosts
文件,把需要解析的地址加入,比如我们此处需要解析的地址是13.2.37.103
重新运行测试程序解析测试,速度有了质的提升。
最后附上测试代码,希望对你有所帮助。
#include <stdio.h>
#include <stdlib.h>
#include <netdb.h>
#include <sys/time.h>
#include <arpa/inet.h>
double getCurrentTime()
{
struct timeval tv;
gettimeofday(&tv, NULL);
return tv.tv_sec + tv.tv_usec * 1e-6;
}
int main()
{
char ip_address[] = "13.2.37.103";
int port_number = 6677:
struct in_addr addr;
inet_pton(AF_INET, ip_address, &addr);
struct hostent host_buf;
struct hostent *host_result;
char buffer[2048];
int herrno;
double start_time , end_time;
start_time = getCurrentTime();
// 使用gethostbyaddr_r函数获取指定ip地址的主机名
gethostbyaddr_r(&addr, sizeof(addr), AF_INET, &host_buf, buffer,sizeof(buffer), &host_result, &herrno);
end_time = getCurrentTime();
if (host_result != NULL)
{
printf("IP Address : %s \n",ip_address);
printf("Host Name : %s \n",host_buf.h_name);
printf("Port Number: %s \n",port_number);
}
else
{
printf("Failed to resolve host for IP : %s \n",ip_address);
}
printf("gethostbyaddr_r time : %.6f seconds \n", end_time - start_time);
start_time = getCurrentTime();
gethostbyname_r(ip_address, &host_buf, buffer, sizeof(buffer), &host_result, &herrno);
end_time = getCurrentTime();
if (host_result != NULL)
{
printf("IP Address : %s \n",ip_address);
printf("Host Name : %s \n",host_buf.h_name);
printf("Port Number: %s \n",port_number);
}
else
{
printf("Failed to resolve host for IP : %s \n",ip_address);
}
printf("gethostbyname_r time : %.6f seconds \n", end_time - start_time);
}