سؤال

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?

هل كانت مفيدة؟

المحلول

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:

Not in POSIX.1-2001. This function first appeared in BSDi and is present on the BSD systems, but with slightly different semantics documented--returning one entry per interface, not per address. This means ifa_addr and other fields can actually be NULL if the interface has no address, and no link-level address is returned if the interface has an IP address assigned. Also, the way of choosing either ifa_broadaddr or ifa_dstaddr differs on various systems.

and

The addresses returned on Linux will usually be the IPv4 and IPv6 addresses assigned to the interface, but also one AF_PACKET address per interface containing lower-level details about the interface and its physical layer. In this case, the ifa_data field may contain a pointer to a struct net_device_stats, defined in , which contains various interface attributes and statistics.

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) returns IP addresses and MAC addresses on local interfaces. Portable between Linux and FreeBSD.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top