在Objective-C中获取MAC地址

时间:2022-11-15 22:33:24

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.

如何在Objective-C中获取计算机的MAC地址?我使用以下代码,但是一旦切换到使用LLVM编译器,它就开始崩溃了。任何人都可以告诉我如何修复此代码或给我新的代码吗?我找到了一种在10.6+中实现它的方法,但我也需要它与10.5一起工作。

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);
}

1 个解决方案

#1


1  

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

Apple实际上有一些示例代码用于从IO注册表获取MAC地址

#1


1  

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

Apple实际上有一些示例代码用于从IO注册表获取MAC地址