gpt4 book ai didi

c - 查找默认网关 ip 地址,而不是解析 proc 文件系统

转载 作者:可可西里 更新时间:2023-11-01 11:50:14 26 4
gpt4 key购买 nike

如何获取默认网关的ip地址?除了从/proc 读取条目,是否有可用的独立 API?

最佳答案

你可以使用libnl这是一个通过 NETLINK 套接字与内核通信的库。

获取默认路由的一个简单示例是(请添加错误检查和所需的 header )

   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;
}

关于c - 查找默认网关 ip 地址,而不是解析 proc 文件系统,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10513704/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com