29

I have an application that uses rest to communicate to a server, i would like to obtain the iphones either mac address or device ID for uniqueness validation, how can this be done?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Daniel
  • 22,363
  • 9
  • 64
  • 71
  • 2
    This is a duplicate of these questions: http://stackoverflow.com/questions/677530/how-can-i-programmatically-get-the-mac-address-of-an-iphone , http://stackoverflow.com/questions/1045608/api-to-get-an-iphones-unique-id – Brad Larson Jul 10 '09 at 17:52

6 Answers6

41

[[UIDevice currentDevice] uniqueIdentifier] is guaranteed to be unique to each device.

Sinkingpoint
  • 7,449
  • 2
  • 29
  • 45
Steven Canfield
  • 7,312
  • 5
  • 35
  • 28
  • 22
    For those new comers to this question, the UDID API is deprecated in iOS 5. To get a unique identifier, you need to turn to iPhones' MAC address instead. – Di Wu Sep 20 '11 at 05:17
  • @diwup, the MAC addr changes depending if the user is on a cellular connection vs Wi-Fi connection right? Or is it the same across both types of network interfaces? – Crashalot Apr 09 '12 at 05:59
  • what is the alternative not deprecated ? – Nicolas Henin Apr 08 '13 at 14:24
  • 2
    use `identifierForVendor` instead in iOS 6+, returns NSUUID object – Sam Nov 08 '13 at 15:58
  • Here's a great article with alternatives: http://www.doubleencore.com/2013/04/unique-identifiers/ – Federico May 19 '14 at 18:45
40

uniqueIdentifier (Deprecated in iOS 5.0. Instead, create a unique identifier specific to your app.)

The docs recommend use of CFUUIDCreate instead of [[UIDevice currentDevice] uniqueIdentifier]

So here is how you generate an unique id in your app

CFUUIDRef uuidRef = CFUUIDCreate(kCFAllocatorDefault);
NSString *uuidString = (NSString *)CFUUIDCreateString(NULL,uuidRef);

CFRelease(uuidRef);

Note that you have to save the uuidString in user defaults or in other place because you can not generate the same uuidString again.

You can use UIPasteboard to store your generated uuid. And if the app will be deleted and reinstalled you can read from UIPasteboard the old uuid. The paste board will be wiped out when the device will be erased.

In iOS 6 they have introduced the NSUUID Class that is designed to create UUIDs strings

Also they added in iOS 6 @property(nonatomic, readonly, retain) NSUUID *identifierForVendor to the UIDevice class

The value of this property is the same for apps that come from the same vendor running on the same device. A different value is returned for apps on the same device that come from different vendors, and for apps on different devices regardless of vendor.

The value of this property may be nil if the app is running in the background, before the user has unlocked the device the first time after the device has been restarted. If the value is nil, wait and get the value again later.

Also in iOS 6 you can use ASIdentifierManager class from AdSupport.framework. There you have

@property(nonatomic, readonly) NSUUID *advertisingIdentifier

Discussion Unlike the identifierForVendor property of the UIDevice, the same value is returned to all vendors. This identifier may change—for example, if the user erases the device—so you should not cache it.

The value of this property may be nil if the app is running in the background, before the user has unlocked the device the first time after the device has been restarted. If the value is nil, wait and get the value again later.

Edit:

Pay attention that the advertisingIdentifier may return

00000000-0000-0000-0000-000000000000

because there seems to be a bug in iOS. Related question: The advertisingIdentifier and identifierForVendor return "00000000-0000-0000-0000-000000000000"

Community
  • 1
  • 1
Alex Terente
  • 12,006
  • 5
  • 51
  • 71
18

For a Mac Adress you could use

#import <Foundation/Foundation.h>

@interface MacAddressHelper : NSObject

+ (NSString *)getMacAddress;

@end

implentation

#import "MacAddressHelper.h"
#import <sys/socket.h>
#import <sys/sysctl.h>
#import <net/if.h>
#import <net/if_dl.h>

@implementation MacAddressHelper

+ (NSString *)getMacAddress
{
  int                 mgmtInfoBase[6];
  char                *msgBuffer = NULL;
  size_t              length;
  unsigned char       macAddress[6];
  struct if_msghdr    *interfaceMsgStruct;
  struct sockaddr_dl  *socketStruct;
  NSString            *errorFlag = NULL;

  // Setup the management Information Base (mib)
  mgmtInfoBase[0] = CTL_NET;        // Request network subsystem
  mgmtInfoBase[1] = AF_ROUTE;       // Routing table info
  mgmtInfoBase[2] = 0;              
  mgmtInfoBase[3] = AF_LINK;        // Request link layer information
  mgmtInfoBase[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);
    return errorFlag;
  }
  // Map msgbuffer to interface message structure
  interfaceMsgStruct = (struct if_msghdr *) msgBuffer;
  // Map to link-level socket structure
  socketStruct = (struct sockaddr_dl *) (interfaceMsgStruct + 1);  
  // Copy link layer address data in socket structure to an array
  memcpy(&macAddress, socketStruct->sdl_data + socketStruct->sdl_nlen, 6);  
  // Read from char array into a string object, into traditional Mac address format
  NSString *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 memory
  free(msgBuffer);
  return macAddressString;
}

@end

Use:

NSLog(@"MAC address: %@",[MacAddressHelper getMacAddress]);
Blazer
  • 14,259
  • 3
  • 30
  • 53
  • that's a lot of work to get the mac address – tybro0103 Aug 09 '12 at 20:39
  • 1
    Is using of Mac addesses is legal? If UUID were privacy hole, then MacAddress can be even bigger hole. – AlfeG Oct 23 '12 at 09:27
  • 1
    for which interface is that mac address? wifi? 3G? – Vame Jan 11 '13 at 10:14
  • 2
    Since iOS7 this is NOT working anymore. As the release notes of iOS 7 states: Two low-level networking APIs that used to return a MAC address now return the fixed value 02:00:00:00:00:00. The APIs in question are sysctl (NET_RT_IFLIST) and ioctl (SIOCGIFCONF). Developers using the value of the MAC address should migrate to identifiers such as -[UIDevice identifierForVendor]. This change affects all apps running on iOS 7. Objective-C Runtime Notes – jules Nov 05 '13 at 08:30
  • @Nathan Sakoetoe: I am getting 02:00:00:00:00:00 Mac address. Is there any other solution to get correct mac address in iOS 8. – Chaaruu Jadhav Mar 25 '15 at 11:54
5

Use this:

NSUUID *id = [[UIDevice currentDevice] identifierForVendor];
NSLog(@"ID: %@", id);
Alexander Volkov
  • 7,904
  • 1
  • 47
  • 44
4

In IOS 5 [[UIDevice currentDevice] uniqueIdentifier] is deprecated.

It's better to use -identifierForVendor or -identifierForAdvertising.

A lot of useful information can be found here:

iOS6 UDID - What advantages does identifierForVendor have over identifierForAdvertising?

Community
  • 1
  • 1
Andrey
  • 2,659
  • 4
  • 29
  • 54
-10

Here, We can find mac address for IOS device using Asp.net C# Code...

.aspx.cs

-
 var UserDeviceInfo = HttpContext.Current.Request.UserAgent.ToLower(); // User's Iphone/Ipad Info.

var UserMacAdd = HttpContext.Current.Request.UserHostAddress;         // User's Iphone/Ipad Mac Address



  GetMacAddressfromIP macadd = new GetMacAddressfromIP();
        if (UserDeviceInfo.Contains("iphone;"))
        {
            // iPhone                
            Label1.Text = UserDeviceInfo;
            Label2.Text = UserMacAdd;
            string Getmac = macadd.GetMacAddress(UserMacAdd);
            Label3.Text = Getmac;
        }
        else if (UserDeviceInfo.Contains("ipad;"))
        {
            // iPad
            Label1.Text = UserDeviceInfo;
            Label2.Text = UserMacAdd;
            string Getmac = macadd.GetMacAddress(UserMacAdd);
            Label3.Text = Getmac;
        }
        else
        {
            Label1.Text = UserDeviceInfo;
            Label2.Text = UserMacAdd;
            string Getmac = macadd.GetMacAddress(UserMacAdd);
            Label3.Text = Getmac;
        }

.class File

public string GetMacAddress(string ipAddress)
    {
        string macAddress = string.Empty;
        if (!IsHostAccessible(ipAddress)) return null;

        try
        {
            ProcessStartInfo processStartInfo = new ProcessStartInfo();

            Process process = new Process();

            processStartInfo.FileName = "arp";

            processStartInfo.RedirectStandardInput = false;

            processStartInfo.RedirectStandardOutput = true;

            processStartInfo.Arguments = "-a " + ipAddress;

            processStartInfo.UseShellExecute = false;

            process = Process.Start(processStartInfo);

            int Counter = -1;

            while (Counter <= -1)
            {                  
                    Counter = macAddress.Trim().ToLower().IndexOf("mac address", 0);
                    if (Counter > -1)
                    {
                        break;
                    }

                    macAddress = process.StandardOutput.ReadLine();
                    if (macAddress != "")
                    {
                        string[] mac = macAddress.Split(' ');
                        if (Array.IndexOf(mac, ipAddress) > -1)                                
                        {
                            if (mac[11] != "")
                            {
                                macAddress = mac[11].ToString();
                                break;
                            }
                        }
                    }
            }
            process.WaitForExit();
            macAddress = macAddress.Trim();
        }

        catch (Exception e)
        {

            Console.WriteLine("Failed because:" + e.ToString());

        }
        return macAddress;

    }
kleopatra
  • 51,061
  • 28
  • 99
  • 211
Nikunj Patel
  • 14
  • 1
  • 2
  • 8
  • tried to improve the code formatting - not entirely successful, as you see ;-) Please edit and improve – kleopatra Apr 23 '13 at 09:14
  • 4
    This question has nothing to do with C# but with objective-c and the Apple SDK! Wrong answer -1 – jAC May 07 '13 at 07:23