在 iOS 中获取设备 ID 或 Mac 地址

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1110278/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 16:08:54  来源:igfitidea点击:

Getting Device ID or Mac Address in iOS

iosobjective-cdevicemac-address

提问by Daniel

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?

我有一个使用 rest 与服务器通信的应用程序,我想获取 iphone 的 mac 地址或设备 ID 以进行唯一性验证,这怎么做?

回答by Steven Canfield

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

[[UIDevice currentDevice] uniqueIdentifier]保证对每个设备都是唯一的。

回答by Alex Terente

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

uniqueIdentifier(在 iOS 5.0 中已弃用。相反,创建一个特定于您的应用程序的唯一标识符。)

The docs recommend use of CFUUIDCreateinstead of [[UIDevice currentDevice] uniqueIdentifier]

文档建议使用CFUUIDCreate而不是[[UIDevice currentDevice] uniqueIdentifier]

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

所以这里是你如何在你的应用程序中生成一个唯一的 id

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.

请注意,您必须将 uuidString 保存在用户默认值或其他位置,因为您无法再次生成相同的 uuidString。

You can use UIPasteboardto 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.

您可以使用UIPasteboard来存储您生成的 uuid。如果应用程序将被删除并重新安装,您可以从 UIPasteboard 读取旧的 uuid。擦除设备时,粘贴板将被擦除。

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

在 iOS 6 中,他们引入了NSUUID 类,旨在创建 UUID 字符串

Also they added in iOS 6 @property(nonatomic, readonly, retain) NSUUID *identifierForVendorto the UIDeviceclass

他们还在 iOS 6 中添加@property(nonatomic, readonly, retain) NSUUID *identifierForVendorUIDevice

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.

对于来自在同一设备上运行的同一供应商的应用程序,此属性的值是相同的。对于来自不同供应商的同一设备上的应用程序以及不同供应商的不同设备上的应用程序,将返回不同的值。

如果应用程序在后台运行,则在设备重启后用户第一次解锁设备之前,此属性的值可能为零。如果值为 nil,则等待稍后再次获取该值。

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

同样在 iOS 6 中,您可以使用AdSupport.framework 中的 ASIdentifierManager类。你有

@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.

讨论 与 UIDevice 的 identifierForVendor 属性不同,向所有供应商返回相同的值。这个标识符可能会改变——例如,如果用户擦除设备——所以你不应该缓存它。

如果应用程序在后台运行,则在设备重启后用户第一次解锁设备之前,此属性的值可能为零。如果值为 nil,则等待稍后再次获取该值。

Edit:

编辑:

Pay attention that the advertisingIdentifiermay return

注意advertisingIdentifier可能返回

00000000-0000-0000-0000-000000000000

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"

因为iOS中似乎有一个错误。相关问题:advertisingIdentifier 和 identifierForVendor 返回“00000000-0000-0000-0000-000000000000”

回答by Blazer

For a Mac Adress you could use

对于 Mac 地址,您可以使用

#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]);

回答by Alexander Volkov

Use this:

用这个:

NSUUID *id = [[UIDevice currentDevice] identifierForVendor];
NSLog(@"ID: %@", id);

回答by Andrey

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

在 IOS 5[[UIDevice currentDevice] uniqueIdentifier]中已弃用。

It's better to use -identifierForVendoror -identifierForAdvertising.

最好使用-identifierForVendor-identifierForAdvertising

A lot of useful information can be found here:

在这里可以找到很多有用的信息:

iOS6 UDID - What advantages does identifierForVendor have over identifierForAdvertising?

iOS6 UDID - identifierForVendor 比 identifierForAdvertising 有什么优势?

回答by Nikunj Patel

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

在这里,我们可以使用 Asp.net C# 代码找到 IOS 设备的 mac 地址...

.aspx.cs

.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

.class 文件

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;

    }