Created
March 6, 2015 17:54
-
-
Save tbl3rd/87122651e682943ce20c to your computer and use it in GitHub Desktop.
MACs for Macs
This file contains hidden or 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
/* Write at result the hardware (MAC) address of the network interface name. | |
Return -1 on failure or 0 on success. | |
*/ | |
static int macForInterface(const char *name, struct sockaddr *result) | |
#ifdef __APPLE__ | |
{ | |
int failed = -1; | |
struct ifaddrs *ifap = NULL; | |
if (0 == getifaddrs(&ifap)) { | |
struct ifaddrs *p = ifap; | |
for (p = ifap; p; p = p->ifa_next) { | |
const int match = | |
p->ifa_addr && | |
p->ifa_addr->sa_family == AF_LINK && | |
0 == strcmp(name, p->ifa_name); | |
if (match) { | |
struct sockaddr_dl *const sadl = | |
(struct sockaddr_dl *)p->ifa_addr; | |
result->sa_len = sadl->sdl_alen; | |
result->sa_family = p->ifa_addr->sa_family; | |
memcpy(result->sa_data, LLADDR(sadl), result->sa_len); | |
failed = 0; | |
break; | |
} | |
} | |
freeifaddrs(ifap); | |
} | |
return failed; | |
} | |
#else | |
{ | |
int fd; | |
struct ifreq ifr; | |
if ((fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) return -1; | |
strcpy(ifr.ifr_name, name); | |
if (ioctl(fd, SIOCGIFHWADDR, &ifr) < 0) return -1; | |
*result = ifr.ifr_hwaddr; | |
if (close(fd) < 0) return -1; | |
return 0; | |
} | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment