Default Gateway in C on Linux

前端 未结 3 960
-上瘾入骨i
-上瘾入骨i 2020-12-09 05:21

How do you find the default gateway of a routing table using C on Linux?

I don\'t want to issue a call to the shell or read a file. There are ioctls for adding and

3条回答
  •  暖寄归人
    2020-12-09 05:59

    You could use/proc/net/route like this:

    int GetDefaultGw ( std::string & gw )
    {
        FILE *f;
        char line[100] , *p , *c, *g, *saveptr;
        int nRet=1;
    
        f = fopen("/proc/net/route" , "r");
    
        while(fgets(line , 100 , f))
        {
            p = strtok_r(line , " \t", &saveptr);
            c = strtok_r(NULL , " \t", &saveptr);
            g = strtok_r(NULL , " \t", &saveptr);
    
            if(p!=NULL && c!=NULL)
            {
                if(strcmp(c , "00000000") == 0)
                {
                    //printf("Default interface is : %s \n" , p);
                    if (g)
                    {
                        char *pEnd;
                        int ng=strtol(g,&pEnd,16);
                        //ng=ntohl(ng);
                        struct in_addr addr;
                        addr.s_addr=ng;
                        gw=std::string( inet_ntoa(addr) );
                        nRet=0;
                    }
                    break;
                }
            }
        }
    
        fclose(f);
        return nRet;
    }
    

提交回复
热议问题