C语言如何在gethostname()中使用超时功能?

C language how to make a timeout function using in gethostname()?

此程序将域从文件读取为字符串,以“\n”为键截断字符串,然后为每个域执行 getostbyname() 函数以将结果信息输入文件。

当我使用gethostbyname时,我想创建一个函数,如果一段时间没有响应则进入失败。我尝试实现并处理超时功能,但是该功能不起作用。

我想到的逻辑是调用gethostbyname(),如果两秒没有响应,在文件中输入fail,然后继续下一个字符串,调用gethostbyname()。

文件量大约是1.5亿个域,所以我只拿了一部分来做例子。

请帮我创建我想要的功能。

这是input.txt

www.naver.com
kbphonemall.com
kbplant.com
k-bplus.com
kbpointreestore.com
kbprint.com
kbprism.com
kbprivatebanking.com
kbpstore.com
kbr9rtudaf5ppy.com
kbrafting.com
kbraille.com
kbrainbank.com
kbrainbow.com
kbrainc.com
kbrainglocal.com
kbrandexpo.com
kbrandingschool.com
kbrandmall.com
kbrandmuseum.com
kbranking.com
k-bread.com
k-breadshop.com
kbreaknews.com
kbreasy.com
kbr-easy.com
kb-rent.com
kbrentacar.com
kb-rentcar.com
kbreport.com
k-brew.com
kbrewtec.com
kbrick.com
kbridge21.com
kbrno.com
k-broad.com
kbrockstar.com
kbrosbeauty.com
kbrosis.com
kbrworks.com
kbs1004.com
kbs123.com
kbs20.com
kbs220.com
kbs3.com
kbs31.com
kbs336.com
kbs358.com
kbs40.com
kbs556.com
kbs5678.com
kbs69.com
kbs7.com
kbs700.com
kbs79.com
kbs87.com
kbs9003.com
kbs911.com
kbs97.com
kbsarchive.com
kbsavers.com
kbsavings.com
kbsavingstar.com
kbsba.com
kbsbaechoo.com
kbsbook.com
kbsc1.com
kbscarf.com
kbsccoding.com
kbscert.com
kbschoolbanking.com
kbscyerrutb.com
kbsec.com
kbsec-greeting.com
kbsecuritynews.com
kbseschool.com
kbsestudy.com
kbsfn.com
kbsgmp.com
kbsgreen.com
kbsgulbee.com
kbs-hip.com
kbsholdings.com
kbshsg.com
kbsisa.com
kbsjeju.com
kbskadt.com
kbskiotmall.com
kbsklt.com
kbskorea.com
kbskorean.com
kbskovo.com
kbsktw.com
kbsktwidea.com
kbslogos.com
kbslove.com
kbs-lse.com
kbsmc-ibd.com
kbsmcob.com
kbsmedi.com
kbsmetal.com
kbsmol.com
kbs-mt.com
kbsmt-academy.com
kbsnd.com
kbsnews.com
kbsnnews.com
kbsonbocns.com
kbsonbodirect.com
kbsonsa.com
kbspetdoc.com
kbsplus.com
kbspro.com
kbsq.com
kbssky.com
kbssomgr.com
kbssports.com
kbsstudy.com
kbstar.com
kbstar2020.com
kbstar21.com
kbstar24.com
kbstarb.com
kbstarcard.com
kbstarclub.com
kbstardirect.com
kbstarebank.com
kbstarfg.com
kbstarfinance.com
kbstarflower.com
kbstarfx.com
kbstarg.com
kbstarir.com
kbstarland.com
kbstarmail.com
kbstarmall.com
kbstarmbank.com
kbstarmoney.com
kbstarpb.com
kbstarsvc.com
kbstarworld.com
kbstarzone.com
kbstbt.com
kbsteel.com
kbstock1.com
kbstock5.com
kbs-travel.com
kbstructure.com
kbstv.com
kbstve.com
kbsuf.com
kbsupercard.com
kbsupporters.com
kbsv.com
kbsvoice.com
kbtac.com
kbtchain.com
kbtechgate.com
kbtechone.com
kbtechpos.com
kbtechshop.com
kbtilbo.com
kb-truck.com
kbtups.com
kbtva.com
kbubi.com
kbuddhism.com
k-buddhism.com
k-buddy.com
kbujejucall.com
kbulgyonews.com
k-bulls.com
kbumall.com
kbund.com
kb-uniform.com
kbusinessnews.com
kbusinfo.com
kbusking.com
kbuvd.com
kbvalve.com
kbvipstock.com
kbweb.com
kbweddingfair.com
kbwel.com
kbwith.com
kbwlab.com
kbwnet.com
kb-world.com
kbworldwide.com
kb-world-wide.com
kby8992.com
kbynews.com
kc005.com
kc04.com
kc0522.com
kc1004.com
kc114.com
kc1357.com
kc1895.com
kc1904.com
kc22.com
kc25.com
kc712.com
kc9479.com
kc97bkyg3tvzgdws.com
kca2009.com
kca21.com
kca7.com
kcaa1.com
kcaa12.com
kcaa21.com
kca-academy.com
kcaawelfare.com
kcabiz.com
kca-charcoal.com
kcadcom.com
k-caddie.com
k-cae.com
kcafrp.com
kcagcf.com
kcagolf.com
kcagym.com
kcahub.com
kcairfiltertech.com
kcakca.com
kcakn.com
kcakorea.com
kcakyrgyz.com
kcallica.com
kcaltrip.com
kcangle.com
kcar.com
k-car.com
kcar2.com
kcaratpay.com
kcarauction.com
kcaraudio.com
kcarb2b.com
kcarcapital.com
kcar-capital.com
kcard.com
kcardirect.com
kcar-direct.com
k-cardirect.com
k-careeraptitude.com
kcarfriends.com
kcarlogis.com
kcarmall.com
kcarnet.com
kcarschool.com
kcarz.com
k-cata.com
kcateam.com
kcatfree.com
kca-therapy.com
kcb4u.com
kcb5.com
kcbc-acc.com
kcbcard.com
kcbec.com
kcbend.com
kcbetrade.com
kcbexchange.com
kcbiea.com
kc-biz.com
kcboltec.com
kcbs119.com
kcbtec.com
kcbtv.com
kcbunion.com
kcc000.com
kcc001.com
kcc002.com
kcc003.com
kcc007.com
kcc1004.com
kcc1122.com
kcc114.com
kcc2.com
kcc21.com
kcc258.com
kcc339.com
kcc5858.com
kcc775.com
kcc7777.com
kcc7979.com
kcc8282.com
kccaedu.com
kccardpos.com
kccarr.com
kccaster.com
kccasters.com
kccauto.com
kccce.com
kccchem.com
kccckorea.com
kcccolorndesign.com
kcccontainer.com
kccdeco.com
kccdepot.com
kccea.com
kccegis.com
kccei.com
kcceleader.com
kccenc.com
kccepost.com
kcceramice.com
kcceye.com
kccf2012.com
kccfilm.com
kccflooring.com
kccgift.com
kccglass.com
kccgroup.com
kcchain.com
kccheavyduty.com
kccholdings.com
kcchomecc.com
kcchomeccinterior.com
kcchwarang.com
kccia.com
kccichem.com
kccinsight.com
kccinterior.com
kccjewelry.com
kcckdong.com
kccks.com
kccmarine.com
kccmaul.com
kccnara.com
kccofficial.com
kccold.com
kccomang.com
kccond.com
kcconveyor.com
kc-coop.com
kc-cottrell.com
kccpaint114.com
kccpaintmall.com
kccplant.com
kccplus.com
kccpr.com
kccrefinish.com
kccrose.com
kccsa.com
kccscleaning.com
kccseoul.com
kccsilicon.com
kccsilicone.com
kccsmms.com
kccssafe.com
kccswitzen-patio.com
kcctm.com
kcctour.com
kccultural.com
kccview.com
kccvma.com
kccwelltztower.com
kccwindow.com
kccwindows.com
kccworld.com
kccycasters.com
kccyes.com
kcdc2020.com
kcdc21.com
kcdcode.com
kcdeaf.com
kcdfarm.com
kcdic.com
kcdkorea.com
kcdoll.com
kcdoor.com
k-cea.com
kcea98.com
kceasw.com
kceautodoor.com
kceccenter.com
kcecctv.com
kcecoin.com
kcecrs.com

这是code

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <time.h>
#include <sys/time.h>
#include <unistd.h>
#include <signal.h>


#define IPATH "example.txt"
#define OPATH "result/output.txt"

struct hostent *host;
int whatthe = 0;

void sig_handler(int signum){
    host = NULL;
}

void dnslookup(char temp1[]){
    host = gethostbyname(temp1);
}

int main(int argc, char *argv[]){
    struct timeval  tv;
    double begin, end;

    gettimeofday(&tv, NULL);
    begin = (tv.tv_sec) * 1000 + (tv.tv_usec) / 1000 ;

    char *ListBuffer;
    int ListSize;

    FILE *InputFile = fopen(IPATH, "r");
    FILE *OutputFile = fopen(OPATH, "w");

    fseek(InputFile, 0, SEEK_END);
    ListSize = ftell(InputFile); //길이를 재고
    ListSize ++; //NULL 문자가 들어갈 자리까지 해줌. 문자열의 끝을 알기 위해서

    ListBuffer = malloc(ListSize); //잰 길이만큼 동적할당
    memset(ListBuffer, 0, ListSize); //할당한 메모리 초기화
    ListBuffer[ListSize] = '[=11=]';

    fseek(InputFile, 0, SEEK_SET);
    fread(ListBuffer, ListSize, 1, InputFile); //읽어와서 동적할당한 배열에 넣기


    char temp[] = {0, };
    char *temp2;

    int count = 0;
    int h_count = 0;


   char *str1 = NULL;
   char *temp1 = strtok_r(ListBuffer, "\n", &str1);
   while (temp1 != NULL){
       dnslookup(temp1);
       signal(SIGALRM,sig_handler);
       alarm(2);

       if (host != NULL){
           fprintf(OutputFile, "%s / %s\n", temp1, inet_ntoa(*(struct in_addr *)host->h_addr_list[0]));
       }
       else{
           fprintf(OutputFile, "%s / %s\n",temp1, "FAIL");
       }
       temp1 = strtok_r(NULL, "\n", &str1);
   }

    fclose(InputFile); //파일 포인터 닫기
    fclose(OutputFile); //파일 포인터 닫기
    free(ListBuffer); // 동적 메모리 해제


    ListBuffer = NULL;

    gettimeofday(&tv, NULL);
    end = (tv.tv_sec) * 1000 + (tv.tv_usec) / 1000 ;

    // 출력
    printf("Execution time %f\n", (end - begin) / 1000);
}

有什么问题?

如果您需要更多解释,我会尽快回答。

感谢您阅读我的问题。祝你有个愉快的一天。

使用 setjmp() & longjmp()alarm() 配对。

#include <setjmp.h>

#define DNS_TIMEOUT 2   // timeout you need
static jmp_buf env;

void sig_handler (int signum) {
    //host = NULL;
    longjmp (env, 1);   // jump to setjmp() location with value 1
}

int dnslookup (const char* domain) {
#define STATUS_TIMEOUT 128      // custom: timeout occurred
    int status = 0;
    signal (SIGALRM, sig_handler);

    if (0 == setjmp(env)) {     // to return here after timeout with return value 1
        alarm (DNS_TIMEOUT);    // setting timeout
        host = gethostbyname (domain);
        signal (SIGALRM, SIG_DFL);
        alarm (0);              // cancel alarm
    } else {                    // after timeout-alarm we're here
        // you may want to record TIMEOUT instead of FAIL
        status = STATUS_TIMEOUT;
        host = NULL;
        //printf ("\nTimeout for %s", domain);
    }
    return status;
}

还有:

    ListBuffer = malloc(ListSize); //잰 길이만큼 동적할당
    memset(ListBuffer, 0, ListSize); //할당한 메모리 초기화 // not necessary
    //ListBuffer[ListSize] = '[=11=]'; // BUFFER-OVERFLOW

...

    char *rmdList = NULL;
    char *domain = strtok_r (ListBuffer, "\n", &rmdList);
    while (domain != NULL) {
        int status = dnslookup (domain);
//        signal (SIGALRM, sig_handler);
//        alarm (2);
        if (host)
            fprintf (OutputFile, "%s / %s\n", domain, inet_ntoa (* (struct in_addr *) host->h_addr_list[0]));
        else if (STATUS_TIMEOUT == status)
            fprintf (OutputFile, "%s / %s\n", domain, "TIMEOUT");
        else
            fprintf (OutputFile, "%s / %s\n", domain, "FAIL");
        domain = strtok_r (NULL, "\n", &rmdList);
    }

也就是说:

The gethostbyname*(), gethostbyaddr*(), herror(), and hstrerror() functions are obsolete. Applications should use getaddrinfo(3), getnameinfo(3), and gai_strerror(3) instead.