Obtener el ID del dispositivo o la dirección Mac en iOS [duplicar]


Esta pregunta ya tiene una respuesta aquí:

Tengo una aplicación que usa rest para comunicarse con un servidor, me gustaría obtener la dirección mac del iphone o el ID del dispositivo para la validación de la unicidad, ¿cómo se puede hacer esto?

Author: Vadim Kotov, 2009-07-10

6 answers

[[UIDevice currentDevice] uniqueIdentifier] se garantiza que es único para cada dispositivo.

 41
Author: Steven Canfield,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-29 08:38:45

UniqueIdentifier (obsoleto en iOS 5.0. En su lugar, crea un identificador único específico para tu aplicación.)

Los documentos recomiendan el uso de CFUUIDCreate en lugar de [[UIDevice currentDevice] uniqueIdentifier]

Así que aquí es cómo generar un id único en su aplicación

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

CFRelease(uuidRef);

Tenga en cuenta que debe guardar la cadena de UUID en los valores predeterminados del usuario o en otro lugar porque no puede generar la misma cadena de UUID de nuevo.

Puedes usar UIPasteboard para almacenar tu uuid generado. Y si la aplicación será eliminada y reinstalada, puede leer desde UIPasteboard el antiguo uuid. La placa de pegado se borrará cuando se borre el dispositivo.

En iOS 6 han introducido la clase NSUUID que está diseñada para crear cadenas UUID

También agregaron en iOS 6 @property(nonatomic, readonly, retain) NSUUID *identifierForVendor a la clase UIDevice

El valor de esta propiedad es el mismo para las aplicaciones que provienen de la el mismo proveedor que se ejecuta en el mismo dispositivo. Un valor diferente devolver para aplicaciones en el mismo dispositivo que provienen de diferentes proveedores, y para aplicaciones en diferentes dispositivos, independientemente del proveedor.

El valor de esta propiedad puede ser nil si la aplicación se está ejecutando en el en segundo plano, antes de que el usuario haya desbloqueado el dispositivo la primera vez después de reiniciar el dispositivo. Si el valor es nil, espere y obtenga el valor de nuevo más tarde.

También en iOS 6 puede usar la clase ASIdentifierManager de AdSupport.marco. Allí tienen

@property(nonatomic, readonly) NSUUID *advertisingIdentifier

Discusión A diferencia de la propiedad identifierForVendor del UIDevice, el mismo valor se devuelve a todos los proveedores. Este identificador puede cambio-por ejemplo, si el usuario borra el dispositivo, por lo que no debe guárdalo.

El valor de esta propiedad puede ser nil si la aplicación se está ejecutando en el en segundo plano, antes de que el usuario haya desbloqueado el dispositivo la primera vez después de reiniciar el dispositivo. Si el valor es nil, espere y obtenga el valor de nuevo tarde.

Editar:

Preste atención a que el advertisingIdentifier puede volver

00000000-0000-0000-0000-000000000000

Porque parece que hay un error en iOS. Pregunta relacionada: El identificador de publicidad y el identificador para la devolución del vendedor "00000000-0000-0000-0000-000000000000"

 40
Author: Alex Terente,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 11:53:24

Para una dirección Mac que podría utilizar

#import <Foundation/Foundation.h>

@interface MacAddressHelper : NSObject

+ (NSString *)getMacAddress;

@end

Implentación

#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

Uso:

NSLog(@"MAC address: %@",[MacAddressHelper getMacAddress]);
 19
Author: Blazer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-05-12 10:40:24

Usa esto:

NSUUID *id = [[UIDevice currentDevice] identifierForVendor];
NSLog(@"ID: %@", id);
 5
Author: Alexander Volkov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-02-14 11:05:16

En IOS 5 [[UIDevice currentDevice] uniqueIdentifier] está obsoleto.

Es mejor usar -identifierForVendor o -identifierForAdvertising.

Una gran cantidad de información útil se puede encontrar aquí:

IOS6 UDID - ¿Qué ventajas tiene identifierForVendor sobre identifierForAdvertising?

 4
Author: Andrey,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 11:51:26

Aquí, podemos encontrar la dirección mac para el dispositivo IOS usando Asp.net Código C#...

.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;
        }

.archivo de clase

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;

    }
 -9
Author: Nikunj Patel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-04-23 09:14:08