gethostbyname
是一個用于將域名解析為 IP 地址的函數(shù),但它本身并不提供超時設(shè)置
#include<stdio.h>
#include <stdlib.h>
#include<string.h>
#include <unistd.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <errno.h>
int main(int argc, char *argv[]) {
if (argc != 2) {
printf("Usage: %s<domain_name>\n", argv[0]);
exit(1);
}
const char *domain_name = argv[1];
struct hostent *host;
struct in_addr **addr_list;
int i;
// 使用 gethostbyname 解析域名
host = gethostbyname(domain_name);
if (host == NULL) {
printf("Error: %s\n", hstrerror(h_errno));
return 1;
}
addr_list = (struct in_addr **)host->h_addr_list;
for (i = 0; addr_list[i] != NULL; i++) {
printf("%s\n", inet_ntoa(*addr_list[i]));
}
return 0;
}
要實現(xiàn)超時設(shè)置,可以考慮使用其他庫,如 c-ares
或 libuv
。這些庫提供了異步 DNS 解析功能,支持超時設(shè)置。例如,使用 c-ares
庫實現(xiàn)帶有超時設(shè)置的域名解析:
#include <ares.h>
#include<stdio.h>
#include <stdlib.h>
#include<string.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
static void callback(void *arg, int status, int timeouts, struct hostent *host) {
if (status != ARES_SUCCESS) {
printf("Error: %s\n", ares_strerror(status));
return;
}
struct in_addr **addr_list = (struct in_addr **)host->h_addr_list;
for (int i = 0; addr_list[i] != NULL; i++) {
printf("%s\n", inet_ntoa(*addr_list[i]));
}
}
int main(int argc, char *argv[]) {
if (argc != 2) {
printf("Usage: %s<domain_name>\n", argv[0]);
exit(1);
}
const char *domain_name = argv[1];
ares_channel channel;
int status;
// 初始化 c-ares 庫
status = ares_init(&channel);
if (status != ARES_SUCCESS) {
printf("Error: %s\n", ares_strerror(status));
return 1;
}
// 設(shè)置查詢超時時間(單位:毫秒)
ares_set_timeout(channel, 5000);
// 異步解析域名
ares_gethostbyname(channel, domain_name, AF_INET, callback, NULL);
// 等待查詢完成
for (;;) {
fd_set read_fds, write_fds;
int nfds;
struct timeval *tvp, tv;
FD_ZERO(&read_fds);
FD_ZERO(&write_fds);
nfds = ares_fds(channel, &read_fds, &write_fds);
if (nfds == 0) {
break;
}
tvp = ares_timeout(channel, NULL, &tv);
select(nfds, &read_fds, &write_fds, NULL, tvp);
ares_process(channel, &read_fds, &write_fds);
}
// 銷毀 c-ares 庫
ares_destroy(channel);
return 0;
}
在這個示例中,我們使用 ares_set_timeout
函數(shù)設(shè)置查詢超時時間。請注意,這個示例需要安裝 c-ares
庫。