2020年7月30日14点39分
更新:
之前写的方法,获取的是wan口的ip和网关,使用过程发现,以有线上网模式为例,获取wan口网关时,若网关中出现连续的1.1,会获取失败,表明该正则表达式是有问题的。即下面这个grep -oE 之后的内容有问题。
ubus call network.interface.wan status | grep nexthop | grep -oE '([0-9]{1,3}.){3}.[0-9]{1,3}'
检查后发现,在’([0-9]{1,3}.){3}.[0-9]{1,3}'中,“{3}”之后多了一个“.”,去掉之后,1.1可以正确获取。或者按照获取ip的表达式来写,也是一样可以正确获取。
ubus call network.interface.wan status | grep nexthop | grep -oE '([0-9]{1,3}.){3}[0-9]{1,3}'
但带来的另外一个问题是,这种方式会有两个返回值,一个是0.0.0.0,另一个是正常的网关。
0.0.0.0
192.168.60.1
如果用这个方法,就需要对两个返回值再做一次处理。暂时没有想好怎么处理,又重新找了其他方式,如下所示:
route -n |awk 'NR==3{print}'| awk '{ print $2; }'
以查询路由表的形式获取。
route -n
获取到路由表,对结果处理,如下,取第三行,第二列的字符串
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
0.0.0.0 192.168.60.1 0.0.0.0 UG 0 0 0 eth0.2
192.168.60.0 0.0.0.0 255.255.254.0 U 0 0 0 eth0.2
192.168.60.1 0.0.0.0 255.255.255.255 UH 0 0 0 eth0.2
192.168.250.0 0.0.0.0 255.255.255.0 U 0 0 0 br-lan
结果为:
192.168.60.1
到此,就可以获取到wan口网关了,欢迎大家补充。
------------------------------------------------------------分割线--------------------------------------------------------------
2020年5月14日18点20分
输入以下命令后,直接返回ip,在函数中使用时,可以封装popen函数来执行shell命令,获取返回结果。
有线上网wan口ip
ubus call network.interface.wan status | grep \"address\" | grep -oE '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'
有线上网wan口网关
ubus call network.interface.wan status | grep nexthop | grep -oE '([0-9]{1,3}.){3}.[0-9]{1,3}'
4g上网模式ip
ubus call network.interface.ppp0 status | grep \"address\" | grep -oE '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'
4g上网模式wan口网关
ubus call network.interface.ppp0 status | grep nexthop | grep -oE '([0-9]{1,3}.){3}.[0-9]{1,3}'
wifi上网模式wan口ip
ubus call network.interface.wwan status | grep \"address\" | grep -oE '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'
wifi上网模式wan口网关
ubus call network.interface.wwan status | grep nexthop | grep -oE '([0-9]{1,3}.){3}.[0-9]{1,3}'
在C语言中调用以上shell命令,返回值就是对应的IP信息。关于C语言中调用shell命令,可以看另一篇文章:C语言获取linux shell命令返回值。
参考: https://blog.csdn.net/u011007991/article/details/52994101