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
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;
}
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.
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/*)