I'm stumped on this one. I'm trying to write a C program for *nix (specifically Linux and BSD) that grabs the MAC address (a.k.a. physical or hardware address) for each network adapter on the machine.
I can get a pointer to the bytes that contain the hardware address, but the problem is I don't know how long the hardware address is. For Ethernet, I know that it's 6 bytes long, but other kinds of adapters have different hardware address lengths. I have the ARPHRD_* value (see <net/if_arp.h> ), which tells me what kind of adapter it is. How can I use this value to determine the number of bytes in the hardware address? Unfortunately, "man 7 netdevice" doesn't tell me what I need to know.
Here's some minimal code:
Code: Select all
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <string.h>
int main(int argc, char** argv) {
int sd;
struct ifreq ifr;
unsigned char* hw_address;
int hw_address_len;
int i;
/* make socket */
sd = socket(PF_INET, SOCK_DGRAM, 0);
if (sd == -1) {
/* insert freak-out code here */
}
/* set interface name (lo, eth0, eth1,..) */
memset(&ifr, 0, sizeof(ifr));
strncpy(ifr.ifr_name, "eth0", IFNAMSIZ);
/* get interface hardware address */
ioctl(sd, SIOCGIFHWADDR, &ifr);
close(sd);
/* get hardware address and length */
hw_address = ifr.ifr_hwaddr.sa_data;
hw_address_len = 6; /* <- what goes here to make it
non-Ethernet-specific? */
/* print out the type of hardware */
printf("ARPHRD_* value of device (see <net/if_arp.h>): %i\n",
ifr.ifr_hwaddr.sa_family);
/* print out hardware address */
printf("Hardware address: ");
for (i = 0; i < hw_address_len; i++) {
printf("%.2x%s", hw_address[i], i==hw_address_len-1 ? "" : ":");
}
printf("\n");
return(0);
}
Thanks!

