[英]DNS lookups using pthreads in C
我正在编写一个解析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解析,系统本身会为您处理。
gethostbyaddr不是线程安全的,因为它返回一个指向静态结构的指针。 如果你正在使用gcc,你可以使用gethostbyaddr_r这是一个线程安全的扩展。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.