2

How do I get the MAC address of the computer in Objective-C? I was using the following code but it started crashing once I switched to using the LLVM compiler. Can anyone tell me how to fix this code or give me new code that works? I found a way to do it in 10.6+, but I need it to work with 10.5 too.

void GetHWAddresses()
{

struct ifconf ifc;
struct ifreq *ifr;
int i, sockfd;
char buffer[BUFFERSIZE], *cp, *cplim;
char temp[80];

for (i=0; i<MAXADDRS; ++i)
{
hw_addrs[i] = NULL;
}


sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0)
{
perror("socket failed");
return;
}


ifc.ifc_len = BUFFERSIZE;
ifc.ifc_buf = buffer;

if (ioctl(sockfd, SIOCGIFCONF, (char *)&ifc) < 0)
{
perror("ioctl error");
close(sockfd);
return;
}



ifr = ifc.ifc_req;

cplim = buffer + ifc.ifc_len;

for (cp=buffer; cp < cplim; )
{
ifr = (struct ifreq *)cp;
if (ifr->ifr_addr.sa_family == AF_LINK)
{
struct sockaddr_dl *sdl = (struct sockaddr_dl *)&ifr->ifr_addr;
int a,b,c,d,e,f;
int i;

strcpy(temp, (char *)ether_ntoa(LLADDR(sdl)));
sscanf(temp, "%x:%x:%x:%x:%x:%x", &a, &b, &c, &d, &e, &f);
sprintf(temp, "%02X:%02X:%02X:%02X:%02X:%02X",a,b,c,d,e,f);

for (i=0; i<MAXADDRS; ++i)
{
if ((if_names[i] != NULL) && (strcmp(ifr->ifr_name, if_names[i]) == 0))
{
if (hw_addrs[i] == NULL)
{
hw_addrs[i] = (char *)malloc(strlen(temp)+1);
strcpy(hw_addrs[i], temp);
break;
}
}
}
}
cp += sizeof(ifr->ifr_name) + max(sizeof(ifr->ifr_addr), ifr->ifr_addr.sa_len);
}

close(sockfd);
}
Paul R
  • 208,748
  • 37
  • 389
  • 560
user817759
  • 111
  • 2
  • 6
  • 2
    http://stackoverflow.com/questions/677530/how-can-i-programmatically-get-the-mac-address-of-an-iphone – Patrick Perini Jul 19 '11 at 17:27
  • 3
    Which MAC address do you want ? There are typically 2 or more on modern Mac systems which have WiFi, Ethernet, Bluetooth, Firewire, etc, all of which can be used for TCP/IP. – Paul R Jul 19 '11 at 17:28
  • @Patrick: that duplicate is for iPhone - the OP has tagged this as Mac. – Paul R Jul 19 '11 at 17:29
  • It *should* be the same. Not positive, but that's why it's a comment and not an answer :) – Patrick Perini Jul 19 '11 at 17:39
  • @Paul R - Looking at it, there's nothing iOS-specific about the linked answers there, so they should work fine for the Mac as well. – Brad Larson Jul 19 '11 at 19:50
  • Patrick, that's the code I use now and it was working just fine until I switched to X-Code 4 and it's now crashing with the LLVM compiler. – user817759 Jul 19 '11 at 20:17
  • Paul, I am looking for the MAC address of a specific IP. Right now I get a list of each adapter and find the one for the correct IP. The code only works with 10.6 though, and the code I used in the past crashes with X-Code 4. – user817759 Jul 19 '11 at 20:19

1 Answers1

1

Apple actually have some example code for getting the MAC address from the IO registry

Tim Davies
  • 824
  • 5
  • 17