Function for obtaining the mac address of an ios Mobile Phone

Source: Internet
Author: User

Recently developed ios project, the number of active mobile phones of the app to be sent to the server. Obtain the unique identifier UUID or MAC address of the mobile phone. The MAC address is obtained because uuid cannot be obtained after IOS5. The code below is highly reusable and can be used as an important reference.

 


# Pragma mark MAC

// Return the local MAC addy

// Courtesy of FreeBSD hackers email list

// Accidentally munged during previous update. Fixed thanks to mlamb.

-(NSString *) macaddress

{

Int mib [6];

Size_t len;

Char * buf;

Unsigned char * ptr;

Struct if_msghdr * ifm;

Struct sockaddr_dl * sdl;


Mib [0] = CTL_NET;

Mib [1] = AF_ROUTE;

Mib [2] = 0;

Mib [3] = AF_LINK;

Mib [4] = NET_RT_IFLIST;


If (mib [5] = if_nametoindex ("en0") = 0 ){

Printf ("Error: if_nametoindex error/n ");

Return NULL;

}


If (sysctl (mib, 6, NULL, & len, NULL, 0) <0 ){

Printf ("Error: sysctl, take 1/n ");

Return NULL;

}


If (buf = malloc (len) = NULL ){

Printf ("cocould not allocate memory. error! /N ");

Return NULL;

}


If (sysctl (mib, 6, buf, & len, NULL, 0) <0 ){

Printf ("Error: sysctl, take 2 ");

Return NULL;

}


Ifm = (struct if_msghdr *) buf;

Sdl = (struct sockaddr_dl *) (ifm + 1 );

Ptr = (unsigned char *) LLADDR (sdl );

NSString * outstring = [NSString stringWithFormat: @ "% 02x % 02x % 02x % 02x % 02x % 02x", * ptr, * (ptr + 1 ), * (ptr + 2), * (ptr + 3), * (ptr + 4), * (ptr + 5)];

Free (buf); www.2cto.com

Return [outstring uppercaseString];


}

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.