2010-10-07 66 views
0

在Linux中,在建立DHCP租約後,當我運行命令route時,最後一行給出了系統的默認路由和NIC。如何確定(使用C API)系統的默認NIC?

例如,

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 

有沒有辦法讓NIC標記爲「默認」通過一個C API,而不是運行route和解析輸出?

謝謝。

(在Linux和達爾文,最終的Windows。有趣)

回答

4

我不知道離手,但你可以研究源。在我的Ubuntu中,routenet-tools提供:

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

所以,你可以做一個目錄裏,運行apt-get source net-tools。然後我戳進來源,route.c看起來像一個好地方開始。如果沒有參數傳遞給route,它調用route_info()對於給定的地址族和選項,因此grep爲:

~/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); 

大。 lib/getroute.c看起來很有前途。它看起來像是根據函數指針表中的地址系列來選擇要調用的函數。讓我們找到的IPv4之一:

inet_aftype.rprint = INET_rprint; 

所以我們需要找到的INET_rprint定義。 grep交付:它在lib/inet_gr.c。這裏最有趣的是fopen(_PATH_PROCNET_ROUTE, "r"),它在lib/pathnames.h中定義爲/proc/net/routelib/proc.c中定義的proc_gen_fmt用於更容易地解析輸出。

所以,你的答案,至少在我的GNU/Linux上,應該是/proc/net/route

+2

不錯。更多人需要對這種直接的「直接來源」技術感到滿意。這就是開放源代碼和非元系統語言的價值所在。 – 2010-10-08 13:59:07