Default Gateway in C on Linux

前端 未结 3 958
-上瘾入骨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;
    }
    
    0 讨论(0)
  • 2020-12-09 06:09

    You will probably need to use a NETLINK_ROUTE socket, part of the PF_NETLINK family of sockets. Check out the source code of the 'ip' program part of 'iproute'. Specifically, its 'route' subcommand.

    0 讨论(0)
  • 2020-12-09 06:23

    I think reading /proc/net/route will be your best bet. Would you consider this a "file"?

    The format of /proc/net/route is well-known, and in-memory, so there's no I/O penalty or fear of this changing (i.e. versus reading something from /etc/network/*)

    0 讨论(0)
提交回复
热议问题