我正在寻找一种在 Linux 和 MacOSX 上用 C 语言获取网络统计信息的方法。 具体来说,我需要监视从系统上每个网络适配器上传和下载的字节数 - 我不需要进行数据包检查,或区分协议,只需一个我可以定期轮询的“总字节”计数器即可没事的。 在 Windows 中,我可以通过 GetIfTable(列出网络适配器)和 GetIfEntry(读取统计信息)使用 iphlpapi.dll 库来执行此操作,但我找不到 Linux/OSX 等效项。 我对 C 的了解相当基础,所以我希望有一个不太复杂的解决方案。 任何帮助将非常感激!
I'm looking for a way to get hold of network stats in C on Linux and MacOSX. Specifically, I need to monitor the number of bytes uploaded and downloaded from each network adapter on the system - I don't need to do packet inspection, or differentiate between protocols, just a 'total bytes' counter which I can poll at intervals would be fine. In Windows I can do this using the iphlpapi.dll library via GetIfTable (to list the network adapters) and GetIfEntry (to read the stats), but I can't find the Linux/OSX equivalents. My knowledge of C is fairly basic so I would appreciate a solution that isn't too involved. Any help would be much appreciated!
发布评论
评论(3)
Darwin netstat 源代码使用 sysctl。
下面是一些在 OSX 上打印输入和输出字节数的代码:
The Darwin netstat source code uses sysctl.
Here's some code that prints the number of bytes in and out on OSX:
我无法与 OSX 对话,但在 Linux 上查看 /proc/net/dev。
如果执行“cat /proc/net/dev”,您应该会看到包括“字节”在内的统计信息——接口传输或接收的数据字节总数。 您可以在自己的程序中读取该文件。
编辑:
我没有阅读你的整个问题。 这篇文章应该帮助您开始使用 /proc 并且有一个关于 /proc/net/ 的部分开发人员。
另外,要列出接口,您可以使用 ioctl ://linux.die.net/man/2/ioctl_list" rel="nofollow noreferrer">SIOCGIFCONF 选项。 您可以通过 Google 搜索有关如何循环返回的数据的不错的代码示例。 或者你可以简单地从上面提到的 /proc.net/dev 数据中提取它,这应该更容易。
I can't speak to OSX but on linux take a look at /proc/net/dev.
If you do 'cat /proc/net/dev' you should see statistics including 'bytes' - the total number of bytes of data transmitted or received by the interface. You can read the file within your own program.
EDIT:
I didn't read your whole question. This article should help you get started with /proc and has a section on /proc/net/dev.
Also, to list the interfaces you can call ioctl with the SIOCGIFCONF option. You can Google for a decent code example on how to loop through the returned data. Or you can simply pull it out of the /proc.net/dev data mentioned above, which should be easier.
在 Linux 上:
/sys/class/net/eth0/statistics/
ip -s link show eth0
on Linux:
/sys/class/net/eth0/statistics/
ip -s link show eth0