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.)
I don’t know off-hand, but you could study the source. On my ubuntu box,
routeis provided bynet-tools:So you could make a directory somewhere, run
apt-get source net-tools. Then I poked into the source, androute.clooked like a good place to start. If there’s no arguments passed toroute, it callsroute_info()for a given address family and options, sogrepfor that:Great.
lib/getroute.clooks 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:So we need to find the definition of
INET_rprint.grepdelivers: it’s inlib/inet_gr.c. The most interesting thing here is thefopen(_PATH_PROCNET_ROUTE, "r"), which is defined inlib/pathnames.has/proc/net/route.proc_gen_fmtdefined inlib/proc.cis used to make parsing the output easier.So your answer, at least on my GNU/Linux box, is to read
/proc/net/route.