Getting gateway to use for a given ip in ANSI C

前端 未结 3 1875
被撕碎了的回忆
被撕碎了的回忆 2020-12-15 18:08

I have looked around like crazy but don\'t get a real answer. I got one example, but that depended on the individuals own library so not much good.

At first I wanted

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-15 19:01

    Maybe this is very old question but I had same problem and I can't find better result. Finally I solved my problem with these code that it has a few changes. So I decide to share it.

    char* GetGatewayForInterface(const char* interface) 
    {
        char* gateway = NULL;
    
        char cmd [1000] = {0x0};
        sprintf(cmd,"route -n | grep %s  | grep 'UG[ \t]' | awk '{print $2}'", interface);
        FILE* fp = popen(cmd, "r");
        char line[256]={0x0};
    
        if(fgets(line, sizeof(line), fp) != NULL)
            gateway = string(line);
    
    
        pclose(fp);
    }
    

提交回复
热议问题