获取路由信息 /proc/net/route
1、前言针对4G,WIFI和有线网络,需要根据参数切换网络路由状态,本文介绍一种通过/proc/net/route获取路由方法。2、route命令静态路由表~ # cat /proc/net/routeIfaceDestinationGatewayFlagsRefCntUseMetricMask...
·
1、前言
针对4G,WIFI和有线网络,需要根据参数切换网络路由状态,本文介绍一种通过/proc/net/route 获取路由方法。
2、route命令
静态路由表
~ # cat /proc/net/route
Iface Destination Gateway Flags RefCnt Use Metric Mask MTU Window IRTT
eth0 00000000 FE00A8C0 0003 0 0 0 00000000 0 0 0
eth0 0000A8C0 00000000 0001 0 0 0 00FFFFFF 0 0 0
~ # route -n
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
0.0.0.0 192.168.0.254 0.0.0.0 UG 0 0 0 eth0
192.168.0.0 0.0.0.0 255.255.255.0 U 0 0 0 eth0
3、实例
static unsigned int GetDefaultGateway()
{
#define PROC_NET_ROUTE "/proc/net/route"
unsigned int dest = 0;
unsigned int gateway = 0;
char buf[256] = {};
FILE *fp = NULL;
char *p = NULL;
fp = fopen(PROC_NET_ROUTE, "r");
if(NULL == fp)
{
printf("GetDefaultGateway open file: %s failure\n", PROC_NET_ROUTE);
return 0;
}
while(fgets(buf, 255, fp))
{
p = strchr(buf, '\t');
if(NULL == p)
{
continue;
}
p++;
sscanf(p, "%X %X", &dest, &gateway);
if((dest != 0) || (0 == gateway))
{
continue;
}
fclose(fp);
return gateway;
}
fclose(fp);
return 0;
}
更多推荐
已为社区贡献1条内容
所有评论(0)