Linux 我可以在不使用 system() 命令的情况下用 C 读/写路由表吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6358431/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 04:32:34  来源:igfitidea点击:

can I read/write the routing table in C without using system() command?

clinuxnetworkingroutes

提问by cateof

I have code written in C. I want to get using C code information that is stored in routing table. Is it possible?

我有用 C 编写的代码。我想使用存储在路由表中的 C 代码信息。是否可以?

采纳答案by Keith

You can open a netlink socket and send route update messages. There is an articleabout how to do this.

您可以打开一个 netlink 套接字并发送路由更新消息。有一篇关于如何做到这一点的文章

回答by Nemo

You can also run "strace route add ..." to see how the routecommand does it.

您还可以运行“strace route add ...”来查看route命令是如何执行的。

On my system, it uses ioctlwith SIOCADDRT. A little searching turns up some sample code.

在我的系统上,它ioctlSIOCADDRT. 稍微搜索一下就会出现一些示例代码

Oddly, the best documentation I have found is from IBM's AS400 man pages.

奇怪的是,我找到的最好的文档来自IBM 的 AS400 手册页

If you just want to read the routing table, you can open and read /proc/net/route. (Again, straceshows that this is how the routecommand does it.) The hex numbers are 32-bit IP addresses in machine-endian form. Try cat /proc/net/route.

如果只想读取路由表,可以打开读取/proc/net/route。(再次strace表明route命令就是这样做的。)十六进制数是机器端格式的 32 位 IP 地址。试试cat /proc/net/route

回答by Jones

If you want to query the routing table only, try to read the file /proc/net/route. It works in my system.

如果只想查询路由表,请尝试读取文件/proc/net/route。它适用于我的系统。