Last active
November 9, 2017 19:19
-
-
Save nuald/f523c1996866779610ad7d805561cb77 to your computer and use it in GitHub Desktop.
Getting MAC addresses
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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