#include <sys/socket.h>#include<sys/sysctl.h>#include<net/if.h>#include<net/if_dl.h>//MAC address//Return The local MAC addy//courtesy of FreeBSD hackers email list//accidentally munged during previous update. Fixed thanks to Erica Sadun & Mlamb.-(NSString *) getmacaddress {intmgmtinfobase[6]; Char*msgbuffer =NULL; size_t length; unsignedCharmacaddress[6]; structIF_MSGHDR *interfacemsgstruct; structSOCKADDR_DL *socketstruct; NSString*errorflag =NULL; //Setup The Management Information Base (MIB)mgmtinfobase[0] = ctl_net;//Request Network Subsystemmgmtinfobase[1] = Af_route;//Routing Table Infomgmtinfobase[2] =0; mgmtinfobase[3] = Af_link;//Request link Layer Informationmgmtinfobase[4] = net_rt_iflist;//Request all configured interfaces//with all configured interfaces requested, get handle index if((mgmtinfobase[5] = If_nametoindex ("En0")) ==0) Errorflag=@"If_nametoindex Failure"; Else { //Get the size of the data available (store in Len) if(Sysctl (Mgmtinfobase,6, NULL, &length, NULL,0) <0) Errorflag=@"sysctl mgmtinfobase Failure"; Else { //Alloc memory based on above call if((Msgbuffer = malloc (length)) = =NULL) Errorflag=@"Buffer allocation Failure"; Else { //Get System Information, store in buffer if(Sysctl (Mgmtinfobase,6, Msgbuffer, &length, NULL,0) <0) Errorflag=@"sysctl msgbuffer Failure"; } } } //Befor going any further ... if(Errorflag! =NULL) { //NSLog (@ "Error:%@", errorflag); returnErrorflag; } //Map Msgbuffer to interface message structureInterfacemsgstruct = (structIF_MSGHDR *) Msgbuffer; //MAP to LINK-LEVEL socket structureSocketstruct = (structSOCKADDR_DL *) (interfacemsgstruct +1); //Copy link Layer address data in socket structure to an arraymemcpy (&macaddress, Socketstruct->sdl_data + Socketstruct->sdl_nlen,6); //Read from char array to a string object, into traditional MAC address formatNSString *macaddressstring = [NSString stringWithFormat:@"%02x:%02x:%02x:%02x:%02x:%02x", macaddress[0], macaddress[1], macaddress[2], macaddress[3], macaddress[4], macaddress[5]]; //NSLog (@ "Mac Address:%@", macaddressstring); //Release the buffer memoryFree (msgbuffer); returnmacaddressstring;}
IOS Get MAC Address