views:

682

answers:

2

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 deleteing routes (SIOCADDRT, SIOCDELRT) and I've found on reference to getting routes (SIOCGRTCONF) but it seems that the version of the kernel I'm using doesn't support SIOCGRTCONF.

+4  A: 

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/*)

slacy
+5  A: 

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.

codelogic
Here is a link to sample code.http://www.linuxquestions.org/questions/linux-networking-3/howto-find-gateway-address-through-code-397078/I've implemented this with some modifications and it works well.
Matt