Get MAC Address

Source: Internet
Author: User

Import the System framework:

#import <ifaddrs.h>

#import <arpa/inet.h>

#include <sys/socket.h>

#include <sys/sysctl.h>

#include <net/if.h>

#include <net/if_dl.h>

Code:

Ip

-(NSString *) getipaddress {

nsstring *address = @ "error";

struct Ifaddrs *interfaces = NULL;

struct Ifaddrs *temp_addr = NULL;

int success = 0;

Retrieve the current Interfaces-returns 0 on success

Success = Getifaddrs (&interfaces);

if (success = = 0) {

Loop through linked list of interfaces

TEMP_ADDR = interfaces;

While (temp_addr! = NULL) {

if (temp_addr->ifa_addr->sa_family = = af_inet) {

Check if interface is En0 which are the WiFi connection on the IPhone

if ([[nsstring stringwithutf8string:temp_addr->ifa_name] isequaltostring:@ "En0"]) {

Get NSString from C String

address = [nsstring stringwithutf8string:inet_ntoa ((struct sockaddr_in *) temp_addr->IFA _ADDR,sin_addr)];

}

}

temp_addr = temp_addr->ifa_next;

}

}

Free memory

Freeifaddrs (interfaces);

return address;

}

Mac

-(NSString *) getmacaddress

{

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("Could 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);

return [outstring uppercasestring];

}

Get MAC Address

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.