views:

39

answers:

1

In Linux, after establishing a DHCP lease, when I run the command route, the last line gives me the system's default route and NIC.

e.g.,

Kernel IP routing table
Destination    Gateway         Genmask        Flags Metric Ref   Use IFace
142.157.138.0  *               255.255.254.0  U     2      0       0 wlan0
link-local     *               255.255.0.0    U     1000   0       0 wlan0
default        142.157.138.1   0.0.0.0        UG    0      0       0 wlan0

Is there a way to get the NIC marked "default" through a C API, instead of running route and parsing the output?

Thanks.

(Interesting in Linux and Darwin, eventually Windows.)

+3  A: 

I don't know off-hand, but you could study the source. On my ubuntu box, route is provided by net-tools:

~$ which route
/sbin/route
~$ dpkg -S /sbin/route
net-tools: /sbin/route

So you could make a directory somewhere, run apt-get source net-tools. Then I poked into the source, and route.c looked like a good place to start. If there's no arguments passed to route, it calls route_info() for a given address family and options, so grep for that:

~/z$ grep -r route_info *
lib/net-support.h:extern int route_info(const char *afname, int flags);
lib/getroute.c: *960221 {1.02} Bernd Eckenfels:        renamed from route_info to getroute.c
lib/getroute.c:int route_info(const char *afname, int options)
netstat.c: *960204 {1.10} Bernd Eckenfels:        aftrans, usage, new route_info, 
netstat.c:      i = route_info(afname, options);
route.c: *       {1.79} Bernd Eckenfels:        route_info
route.c:    i = route_info(afname, options);

Great. lib/getroute.c looks promising. It looks like it's choosing which function to call based of a table of function pointers, sorted by address family. Let's find the IPv4 one:

inet_aftype.rprint = INET_rprint;

So we need to find the definition of INET_rprint. grep delivers: it's in lib/inet_gr.c. The most interesting thing here is the fopen(_PATH_PROCNET_ROUTE, "r"), which is defined in lib/pathnames.h as /proc/net/route. proc_gen_fmt defined in lib/proc.c is used to make parsing the output easier.

So your answer, at least on my GNU/Linux box, is to read /proc/net/route.

Jack Kelly
Nice. More people need to be comfortable with this straightforward "straight to the source" technique. This is what makes open-source and non-meta systems languages worth it.
Matt Joiner