Получение идентификатора устройства или Mac-адреса в iOS [дубликат]
-
12-09-2019 - |
Вопрос
На этот вопрос уже есть ответ здесь:
У меня есть приложение, которое использует rest для связи с сервером, я хотел бы получить mac-адрес iphone или идентификатор устройства для проверки уникальности, как это можно сделать?
Решение
[[UIDevice currentDevice] uniqueIdentifier]
гарантированно является уникальным для каждого устройства.
Другие советы
Уникальный идентификатор (устарел в iOS 5.0.Вместо этого создайте уникальный идентификатор, специфичный для вашего приложения.)
Документы рекомендуют использовать CFUUID Создать вместо того , чтобы [[UIDevice currentDevice] uniqueIdentifier]
Итак, вот как вы генерируете уникальный идентификатор в своем приложении
CFUUIDRef uuidRef = CFUUIDCreate(kCFAllocatorDefault);
NSString *uuidString = (NSString *)CFUUIDCreateString(NULL,uuidRef);
CFRelease(uuidRef);
Обратите внимание, что вам необходимо сохранить UUIDString в user defaults или в другом месте, потому что вы не сможете сгенерировать ту же UUIDString снова.
Вы можете использовать UIPasteboard - картонная коробка чтобы сохранить ваш сгенерированный uuid.И если приложение будет удалено и переустановлено, вы можете прочитать из UIPasteboard старый uuid.Плата для наклеивания будет стерта, когда устройство будет удалено.
В iOS 6 они представили Класс NSUUID это предназначено для создания строк UUID
Также они добавлены в iOS 6 @property(nonatomic, readonly, retain) NSUUID *identifierForVendor
к тому Жидкостное устройство класс
Значение этого свойства одинаково для приложений, которые исходят от же поставщиков, работающих на одном устройстве.Возвращается другое значение для приложений на одном устройстве, которые поставляются от разных поставщиков, и для приложений на разных устройствах независимо от поставщика.
Значение этого свойства может быть равно нулю, если приложение запущено в фоновом режиме до того, как пользователь разблокировал устройство в первый раз после перезапуска устройства.Если значение равно нулю, подождите и получите значение снова позже.
Также в iOS 6 вы можете использовать Сторонний идентификатор - менеджер класс из AdSupport.framework.Там у вас есть
@property(nonatomic, readonly) NSUUID *advertisingIdentifier
Обсуждение В отличие от свойства identifierForVendor пользовательского устройства, одно и то же значение возвращается всем поставщикам.Этот идентификатор может измениться — например, если пользователь удалит устройство, — поэтому вам не следует кэшировать его.
Значение этого свойства может быть равно нулю, если приложение запущено в фоновом режиме до того, как пользователь разблокировал устройство в первый раз после перезапуска устройства.Если значение равно нулю, подождите и получите значение снова позже.
Редактировать:
Обратите внимание, что advertisingIdentifier
может вернуться
00000000-0000-0000-0000-000000000000
потому что, похоже, в iOS есть ошибка.Связанный с этим вопрос: Идентификаторы advertisingIdentifier и identifierForVendor возвращают "00000000-0000-0000-0000-000000000000".
Для Mac-адреса вы могли бы использовать
#import <Foundation/Foundation.h>
@interface MacAddressHelper : NSObject
+ (NSString *)getMacAddress;
@end
внедрение
#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
Использование:
NSLog(@"MAC address: %@",[MacAddressHelper getMacAddress]);
Используй это:
NSUUID *id = [[UIDevice currentDevice] identifierForVendor];
NSLog(@"ID: %@", id);
В IOS 5 [[UIDevice currentDevice] uniqueIdentifier]
является устаревшим.
Это лучше использовать -identifierForVendor
или -identifierForAdvertising
.
Много полезной информации можно найти здесь:
iOS6 UDID - Какие преимущества имеет identifierForVendor по сравнению с identifierForAdvertising?
Здесь мы можем найти mac-адрес для устройства IOS, используя Asp.net Код на 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;
}
.файл класса
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;
}