Skip to content

Instantly share code, notes, and snippets.

@yuxincs
Forked from nuald/listmacaddrs.c
Last active June 5, 2018 17:39
Show Gist options
  • Save yuxincs/65f6872e4d7a06cc9e386e9b8cefc8e0 to your computer and use it in GitHub Desktop.
Save yuxincs/65f6872e4d7a06cc9e386e9b8cefc8e0 to your computer and use it in GitHub Desktop.
Getting MAC addresses
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <ifaddrs.h>
// works on Linux and macOS
#ifdef AF_LINK
#include <net/if_dl.h>
unsigned char *get_ptr(struct ifaddrs *ifaptr)
{
if (ifaptr->ifa_addr->sa_family == AF_LINK)
return (unsigned char *)LLADDR((struct sockaddr_dl *)(ifaptr)->ifa_addr);
else
return NULL;
}
#endif
#ifdef AF_PACKET
#include <netpacket/packet.h>
unsigned char *get_ptr(struct ifaddrs *ifaptr)
{
if (ifaptr->ifa_addr->sa_family == AF_PACKET)
return (unsigned char *)((struct sockaddr_ll*)ifaptr->ifa_addr)->sll_addr;
else
return NULL;
}
#endif
// sample usage
void get_mac_address(void)
{
struct ifaddrs *ifap;
unsigned char *ptr;
if (getifaddrs(&ifap) == 0)
{
for (struct ifaddrs *ifaptr = ifap; ifaptr != NULL; ifaptr = ifaptr->ifa_next)
{
ptr = get_ptr(ifaptr);
if (ptr != NULL)
{
printf("%s: %02x:%02x:%02x:%02x:%02x:%02x\n",
(ifaptr)->ifa_name,
*ptr, *(ptr + 1), *(ptr + 2), *(ptr + 3), *(ptr + 4), *(ptr + 5));
}
}
freeifaddrs(ifap);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment