gpt4 book ai didi

c - 在 C 中使用 pthread 进行 DNS 查找

转载 作者:行者123 更新时间:2023-11-30 14:20:10 27 4
gpt4 key购买 nike

我正在编写一个解析 HTML 的程序,但是,当它解析多个 HTML 文件时,我需要对 IP 集合执行 DNS 查找。我正在考虑使用 pthreads 来执行查找任务。

您建议这样做吗?我是否需要多个线程来完成这项任务?我可能会遇到哪些潜在问题?如有任何反馈,我们将不胜感激。

这就是我的想法......

#include <pthread.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void *ip2host(void *ips[][2]){
struct hostent *hent;
struct in_addr addr;
int i;
for (i=0;i<3;i++) {
if(!inet_aton(ips[i][0], &addr))
return NULL;

if((hent = gethostbyaddr((char *)&(addr.s_addr), sizeof(addr.s_addr), AF_INET))){
ips[i][1] = malloc (strlen (hent->h_name) + 1);
strcpy(ips[i][1], hent->h_name);
}
}
return NULL;
}

int main(){
char *ips[][2] = {
{"199.21.99.110", NULL},
{"66.249.73.55", NULL},
{"74.125.225.34", NULL}
};

pthread_t thread1;
if(pthread_create(&thread1, NULL, ip2host, &ips)) {
fprintf(stderr, "Error creating thread\n");
return 1;
}

// parse html files
int y = 0;
while(++y < 100000);
printf("y increment finished\n");

if(pthread_join(thread1, NULL)) {
fprintf(stderr, "Error joining thread\n");
return 1;
}
int i;
for(i=0; i<3; i++) {
printf("%s\n", ips[i][1]);
}
return 0;
}

最佳答案

只需将 DNS 查找视为连接过程的一部分,并在 connect() 之前进行即可。无论如何,这就是您需要它的地方,如果 IP 在您需要时可能尚未准备好,那么在另一个线程中执行此操作有什么意义?

记住 connect() 会挂起你的线程,直到连接也稳定为止,因此解析 IP 并不是这里唯一花费的时间。

另外,不用担心缓存 DNS 解析,系统本身会为您处理好这个问题。

关于c - 在 C 中使用 pthread 进行 DNS 查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15715313/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com