[英]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.