Conseguir la identificación del dispositivo o la dirección Mac en IOS [duplicado]
-
12-09-2019 - |
Pregunta
Esta pregunta ya tiene una respuesta aquí:
Tengo una aplicación que utiliza resto de comunicarse con un servidor, me gustaría obtener los iphones cualquiera de las direcciones MAC o ID de dispositivo para la validación singularidad, ¿cómo se puede hacer esto?
Solución
[[UIDevice currentDevice] uniqueIdentifier]
se garantiza que sea único para cada dispositivo.
Otros consejos
uniqueIdentifier (en desuso en IOS 5.0. En su lugar, crear un identificador único específico para su aplicación.)
Los documentos recomiendan el uso de CFUUIDCreate en lugar de [[UIDevice currentDevice] uniqueIdentifier]
Así que aquí es cómo se genera un identificador único en su aplicación
CFUUIDRef uuidRef = CFUUIDCreate(kCFAllocatorDefault);
NSString *uuidString = (NSString *)CFUUIDCreateString(NULL,uuidRef);
CFRelease(uuidRef);
Tenga en cuenta que usted tiene que guardar el uuidString en valores predeterminados del usuario o en otro lugar porque no se puede generar la misma uuidString de nuevo.
Puede utilizar UIPasteboard para almacenar su UUID generado. Y si se borra y vuelve a instalar la aplicación se puede leer desde el viejo UIPasteboard UUID. La junta de pasta será eliminado cuando se borrará el dispositivo.
En iOS 6 que han introducido el NSUUID Clase que está diseñado para crear cadenas UUID
También se añadió en IOS 6 @property(nonatomic, readonly, retain) NSUUID *identifierForVendor
a la clase UIDevice
El valor de esta propiedad es la misma para las aplicaciones que vienen de la mismo proveedor que se ejecuta en el mismo dispositivo. Se devuelve un valor diferente para aplicaciones en el mismo dispositivo que vienen de diferentes proveedores, y para aplicaciones en diferentes dispositivos independientemente del proveedor.
El valor de esta propiedad puede ser nulo si la aplicación se está ejecutando en el fondo, antes de que el usuario ha desbloqueado el dispositivo por primera vez después de que el dispositivo ha sido reiniciado. Si el valor es nulo, esperar y conseguir el valor nuevo más tarde.
También en IOS 6 puede utilizar clase ASIdentifierManager de AdSupport.framework. Hay que tener
@property(nonatomic, readonly) NSUUID *advertisingIdentifier
A diferencia de la propiedad Discusión identifierForVendor del UIDevice, el mismo valor se devuelve a todos los proveedores. Esto puede identificador cambiar, por ejemplo, si el usuario borra el dispositivo, de modo que no debería almacenar en caché.
El valor de esta propiedad puede ser nulo si la aplicación se está ejecutando en el fondo, antes de que el usuario ha desbloqueado el dispositivo por primera vez después de que el dispositivo ha sido reiniciado. Si el valor es nulo, esperar y conseguir el valor nuevo más tarde.
Editar:
Tener en cuenta que la advertisingIdentifier
puede volver
00000000-0000-0000-0000-000000000000
porque parece que hay un error en iOS. pregunta relacionada: El retorno advertisingIdentifier y identifierForVendor "00000000-0000-0000 -0000" -000000000000
En un Mac Adress podría utilizar
#import <Foundation/Foundation.h>
@interface MacAddressHelper : NSObject
+ (NSString *)getMacAddress;
@end
implementació
#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]);
Utilice esta:
NSUUID *id = [[UIDevice currentDevice] identifierForVendor];
NSLog(@"ID: %@", id);
En IOS es obsoleto 5 [[UIDevice currentDevice] uniqueIdentifier]
.
Es mejor utilizar -identifierForVendor
o -identifierForAdvertising
.
Una gran cantidad de información útil se puede encontrar aquí:
iOS6 UDID - ¿Qué ventajas tiene sobre identifierForVendor identifierForAdvertising?
Aquí, podemos encontrar la dirección MAC para el dispositivo IOS con Asp.net C # Código ...
.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 Archivo
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;
}