Is there a way to get interface's MAC address via getifaddrs()
?
I already have this, to get IP addresses, but I have kinda missed MAC
. Ive tried to look for the information in getifaddrs()
, but there is nothing about MAC
addresses
struct ifaddrs *iflist, *iface;
if (getifaddrs(&iflist) < 0)
{
perror("getifaddrs");
}
char addrp[INET6_ADDRSTRLEN];
char macp[INET6_ADDRSTRLEN];
int i=0;
for (iface = iflist; iface; iface = iface->ifa_next)
{
int af = iface->ifa_addr->sa_family;
const void *addr;
const void *mac;
switch (af)
{
case AF_INET:
addr = &((struct sockaddr_in *)iface->ifa_addr)->sin_addr;
break;
//get mac address somehow?
default:
addr = NULL;
}
if (addr)
{
if (inet_ntop(af, addr, addrp, sizeof addrp) == NULL)
{
perror("inet_ntop");
continue;
}
if (inet_ntop(af, mac, macp, sizeof macp) == NULL) // this is already for MAC add
{
perror("inet_ntop");
continue;
}
if (strcmp(addrp, "127.0.0.1") != 0)
{
strcat(tableO[i].IPaddr, addrp);
strcat(tableO[i].MACaddr, macp);
i++;
}
}
Thanks
the file /sys/class/net/eth0/address carries your mac adress as simple string you can read with fopen() / fscanf() / fclose() . Nothing easier than that. And if you want to support other network interfaces than eth0 (and you probably want), then simply use opendir() / readdir() / closedir() on /sys/class/net/ .
The getifaddrs() function stores a reference to a linked list of ifaddrs structures, one structure per interface. The end of the linked list of structures is indicated by a structure with an ifa_next of NULL.
The getifaddrs() function creates a linked list of structures describing the network interfaces of the local system, and stores the address of the first item of the list in *ifap.
On Linux, you'd do something like this
case AF_PACKET: {
struct sockaddr_ll *s = (struct sockaddr_ll*)iface->ifa_addr;
int i;
int len = 0;
for(i = 0; i < 6; i++)
len+=sprintf(macp+len,"%02X%s",s->sll_addr[i],i < 5 ? ":":"");
}
Though, there might be more members of the struct sockaddr_ll you'd want to inspect, see here for a description.
getifaddrs() already provides the MAC address associated with each interface. On Linux, when you bump into a family == AF_PACKET that is the MAC address. Same thing on OSX / BSD but in that case the family will be AF_LINK.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With