Linux下C:发现默认网关的IP地址,而不是解析proc文件系统 [英] Linux C: find default gateway ip address , rather than parsing proc filesystem
本文介绍了Linux下C:发现默认网关的IP地址,而不是解析proc文件系统的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我应该如何获取默认网关的IP地址?而不是阅读的/ proc条目,有没有独立的API可用?
How should I obtain the ip address of default gateway ? Rather than read entries from /proc , is there any standalone API useable ?
推荐答案
您可以使用 libnl 这是一个库通过NETLINK插座与内核通信。
you can use libnl which is a library to communicate with the kernel via NETLINK sockets.
一个简单的例子来获取默认的路线会(请加错误检查和必要的头)
a simple example to get the default route would be (please add error checking and the needed headers)
void cb_route (struct nl_object *cb, void *arg) {
struct rtnl_route *route = (struct rtnl_route*) cb;
/* do what you need to do with rtnl_route object
* e.g. copy it to arg, etc.
*/
struct nl_addr *tmp_addr;
tmp_addr = rtnl_route_get_gateway(route);
len = nl_addr_get_len(tmp_addr);
memcpy(arg, nl_addr_get_binary_addr(tmp_addr), len);
}
int get_route () {
struct nl_handle *nlh;
struct nl_cache *route_cache;
struct rtnl_route *filter;
struct nl_addr *dst;
char *gw = malloc(16); //enough room for IPv6 if needed
char n = '0';
nlh = nl_handle_alloc();
if (!nlh)
return -1;
nl_connect(nlh, NETLINK_ROUTE);
route_cache = rtnl_route_alloc_cache();
if (nl_cache_is_empty(route_cache))
return 0;
dst = nl_addr_build(AF_INET, &n, 0);
filter = rtnl_route_alloc();
rtnl_route_set_scope(filter, RT_SCOPE_UNIVERSE);
rtnl_route_set_family(filter, AF_INET);
rtnl_route_set_table(filter, RT_TABLE_MAIN);
rtnl_route_set_dst(filter, dst);
nl_cache_foreach_filter(route_cache, (struct nl_object*) filter, cb_filter_route, gw);
/* gw should now contain the binary representation of the default gw. use inet_ntop to convert it */
return 0;
}
这篇关于Linux下C:发现默认网关的IP地址,而不是解析proc文件系统的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文