在C中查找Linux和FreeBSD上的MAC地址
我试图找出 MAC 地址,并设法在 Linux 中使用 sysctl 创建工作解决方案,问题是,该解决方案不适用于我正在开发的 FreeBSD 版本。除了使用 sysctl 之外,还有什么方法可以找出 C 中的 mac 地址吗?
I am trying to find out MAC address and I managed to create working solution using sysctl in Linux, problem is, that this solution is not working on FreeBSD version I am developing on. Is there any way I can find out mac address in C other than using sysctl?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用 libpcap 库。这是您能找到的最多平台的方式。
该库用于网络嗅探器和入侵检测,以及专用于测量其他网络统计数据。 nethogs 实用程序用于测量每个进程的网络使用情况,iftop 用于测量每个计算机/端口的带宽使用情况。在许多角色中都非常灵活。
用 C 编写,但有一些其他语言的包装器。
1: http://en.wikipedia.org/wiki/Pcap
[2]: http://www.tcpdump.org
[3]: http://sourceforge.net/projects/libpcap/
编辑:
这是一个完整、准确且有效的示例,其中包含详细的代码和功能:
http://coderrr. wordpress.com/2008/03/07/get-the-mac-address-of-a-local-ip/
这里有很多教程,源代码是你最好的朋友。
编辑 2: blaze 指出 getifaddrs(3) 似乎可以完成这项工作,只是有一些警告,它是一个非 posix 函数。是 glibc linux 支持但不提供文档的 bsd 函数。几乎是一个未记录的功能:-)
所有文档都是手册页和来自 kernel.org 的手册:
和
因此,它的行为可能会有所不同,并且您可能必须
#ifndef
进行编译。kernel.org 手册页位于 http:// www.kernel.org/doc/man-pages/online/pages/man3/getifaddrs.3.html 确实提供了示例代码,这可能会有所帮助。与上面的链接相比,我本地的 Linux 手册页相当差。
我仍然认为 libpcap 更具可移植性,因为其他人已经完成了所有可移植性工作以及通过使用它获得的所有额外功能。
希望这有帮助。
Use the libpcap library. Its the most multi platform way you can find.
This library is used on network sniffers and intrusion detections, as well as dedicate measuring other network statistics. The nethogs utility to measure per process network usage, the iftop used to measure per machine/port bandwidth usage. Is very flexible in many roles.
Is written in C but there are some wrappers for other languages.
1: http://en.wikipedia.org/wiki/Pcap
[2]: http://www.tcpdump.org
[3]: http://sourceforge.net/projects/libpcap/
Edit:
here is a complete and exact and working example with the code and functions detailed:
http://coderrr.wordpress.com/2008/03/07/get-the-mac-address-of-a-local-ip/
There are plenty of tutorials and the source code is your best friend.
Edit 2: blaze pointed out
getifaddrs(3)
which seems to do the job, just a few caveats, its a non-posix function. Is a bsd function which glibc linux supports but do NOT documents. Is almost an undocumented featured :-)All documentation are man pages and from the manual at kernel.org:
and
So it may vary in behavior and you'll may have to
#ifndef
compile anyway.The kernel.org man page at http://www.kernel.org/doc/man-pages/online/pages/man3/getifaddrs.3.html does provides example code in it, which may be helpful. My local linux man page is rather poor in comparison to the above linked.
I still think that libpcap is more portable if only because someone else had done all the portability work and all the extra features you gain by using it.
Hope this helps.
getifaddrs(3) 返回本地接口上的 IP 地址和 MAC 地址。可在 Linux 和 FreeBSD 之间移植。
getifaddrs(3) returns IP addresses and MAC addresses on local interfaces. Portable between Linux and FreeBSD.