Getting gateway to use for a given ip in ANSI C

前端 未结 3 1873
被撕碎了的回忆
被撕碎了的回忆 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 18:57

    I decided to go the "quick-and-dirty" way to start with and read out the ip from /proc/net/route using netstat -rm.

    I thought I'd share my function... Note however that there is some error in it and prehaps you could help me find it and I'll edit this to be without faults. The function take a iface name like eth0 and returns the ip of the gateway used by that iface.

    char* GetGatewayForInterface(const char* interface) {
      char* gateway = NULL;
    
      FILE* fp = popen("netstat -rn", "r");
      char line[256]={0x0};
    
      while(fgets(line, sizeof(line), fp) != NULL)
      {    
        /*
         * Get destination.
         */
        char* destination;
        destination = strndup(line, 15);
    
        /*
         * Extract iface to compare with the requested one
         * todo: fix for iface names longer than eth0, eth1 etc
         */
        char* iface;
        iface = strndup(line + 73, 4);
    
    
        // Find line with the gateway
        if(strcmp("0.0.0.0        ", destination) == 0 && strcmp(iface, interface) == 0) {
            // Extract gateway
            gateway = strndup(line + 16, 15);
        }
    
        free(destination);
        free(iface);
      }
    
      pclose(fp);
      return gateway;
    }
    

    The problem with this function is that when I leave pclose in there it causes a memory corruption chrash. But it works if I remove the pclose call (but that would not be a good solution beacuse the stream would remain open.. hehe). So if anyone can spot the error I'll edit the function with the correct version. I'm no C guru and gets a bit confused about all the memory fiddling ;)

提交回复
热议问题