Skip to content

Instantly share code, notes, and snippets.

@heckj
Created September 2, 2011 05:57
Show Gist options
  • Save heckj/1187999 to your computer and use it in GitHub Desktop.
Save heckj/1187999 to your computer and use it in GitHub Desktop.
Get MAC addresses of all interfaces
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <net/if.h>
#include <ifaddrs.h>
#include <errno.h>
#include <net/if_dl.h>
#if ! defined(IFT_ETHER)
#define IFT_ETHER 0x6/* Ethernet CSMACD */
#endif
@implementation UIDevice (Extensions)
- (NSDictionary *)interfaces
{
NSMutableDictionary *theDictionary = [NSMutableDictionary dictionary];
BOOL success;
struct ifaddrs * addrs;
const struct ifaddrs * cursor;
const struct sockaddr_dl * dlAddr;
const uint8_t * base;
success = getifaddrs(&addrs) == 0;
if (success)
{
cursor = addrs;
while (cursor != NULL)
{
if ( (cursor->ifa_addr->sa_family == AF_LINK) && (((const struct sockaddr_dl *)cursor->ifa_addr)->sdl_type == IFT_ETHER) )
{
fprintf(stderr, "%s:", cursor->ifa_name);
dlAddr = (const struct sockaddr_dl *)cursor->ifa_addr;
base = (const uint8_t *) &dlAddr->sdl_data[dlAddr->sdl_nlen];
NSString *theKey = [NSString stringWithUTF8String:cursor->ifa_name];
NSString *theValue = [NSString stringWithFormat:@"%02x:%02x:%02x:%02x:%02x:%02x", base[0], base[1], base[2], base[3], base[4], base[5]];
[theDictionary setObject:theValue forKey:theKey];
}
cursor = cursor->ifa_next;
}
freeifaddrs(addrs);
}
return(theDictionary);
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment