获取mac地址的代码
//头文件记不清楚是哪些了,忘记那些是不是都需要
#import<ifaddrs.h>
#import<arpa/inet.h>
#include<sys/socket.h>
#include<sys/sysctl.h>
#include<net/if.h>
#include<net/if_dl.h>
-(NSString*)macaddress
{
intmgmtInfoBase[6];
char*msgBuffer=NULL;
size_tlength;
unsignedcharmacAddress[6];
structif_msghdr*interfaceMsgStruct;
structsockaddr_dl*socketStruct;
NSString*errorFlag=NULL;
//SetupthemanagementInformationBase(mib)
mgmtInfoBase[0]=CTL_NET;//Requestnetworksubsystem
mgmtInfoBase[1]=AF_ROUTE;//Routingtableinfo
mgmtInfoBase[2]=0;
mgmtInfoBase[3]=AF_LINK;//Requestlinklayerinformation
mgmtInfoBase[4]=NET_RT_IFLIST;//Requestallconfiguredinterfaces
//Withallconfiguredinterfacesrequested,gethandleindex
if((mgmtInfoBase[5]=if_nametoindex("en0"))==0)
errorFlag=@"if_nametoindexfailure";
else
{
//Getthesizeofthedataavailable(storeinlen)
if(sysctl(mgmtInfoBase,6,NULL,&length,NULL,0)<0)
errorFlag=@"sysctlmgmtInfoBasefailure";
else
{
//Allocmemorybasedonabovecall
msgBuffer=(char*)malloc(length);
if((msgBuffer)==NULL)
errorFlag=@"bufferallocationfailure";
else
{
//Getsysteminformation,storeinbuffer
if(sysctl(mgmtInfoBase,6,msgBuffer,&length,NULL,0)<0)
errorFlag=@"sysctlmsgBufferfailure";
}
}
}
//Beforgoinganyfurther...
if(errorFlag!=NULL)
{
//DLog(@"Error:%@",errorFlag);
returnerrorFlag;
}
//Mapmsgbuffertointerfacemessagestructure
interfaceMsgStruct=(structif_msghdr*)msgBuffer;
//Maptolink-levelsocketstructure
socketStruct=(structsockaddr_dl*)(interfaceMsgStruct+1);
//Copylinklayeraddressdatainsocketstructuretoanarray
memcpy(&macAddress,socketStruct->sdl_data+socketStruct->sdl_nlen,6);
//Readfromchararrayintoastringobject,intotraditionalMacaddressformat
NSString*macAddressString=[NSStringstringWithFormat:@"%02X%02X%02X%02X%02X%02X",
macAddress[0],macAddress[1],macAddress[2],
macAddress[3],macAddress[4],macAddress[5]];
//DLog(@"MacAddress:%@",macAddressString);
//Releasethebuffermemory
free(msgBuffer);
returnmacAddressString;
}
返回mac地址字符串