Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Getting MAC addresses
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <ifaddrs.h>
#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);
}
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;
}
return NULL;
}
#endif
int listmacaddrs(void) {
struct ifaddrs *ifap, *ifaptr;
unsigned char *ptr;
if (getifaddrs(&ifap) == 0) {
for (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);
return 1;
} else {
return 0;
}
}
extern int
main(int argc, char* argv[]) {
return listmacaddrs();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.