很多时候需要搜集用户的MAC地址或者UID来进行用户的身份确认, UID和MAC地址都可以保持唯一性.

  • 获取UID
1
+ ( NSString *) getHardwareUUID {
  NSTask *task;
  task = [[NSTask alloc] init];
  [task setLaunchPath: @"/usr/sbin/ioreg"];
  
  //ioreg -rd1 -c IOPlatformExpertDevice | grep -E '(UUID)'
  
  NSArray *arguments;
  arguments = [NSArray arrayWithObjects: @"-rd1", @"-c",@"IOPlatformExpertDevice",nil];
  [task setArguments: arguments];
  
  NSPipe *pipe;
  pipe = [NSPipe pipe];
  [task setStandardOutput: pipe];
  
  NSFileHandle *file;
  file = [pipe fileHandleForReading];
  
  [task launch];
  
  NSData *data;
  data = [file readDataToEndOfFile];
  
  NSString *string;
  string = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
  
  NSString *key = @"IOPlatformUUID";
  NSRange range = [string rangeOfString:key];
  
  NSInteger location = range.location + [key length] + 5;
  NSInteger length = 32 + 4;
  range.location = location;
  range.length = length;
  
  NSString *UUID = [string substringWithRange:range];
  
  UUID = [UUID stringByReplacingOccurrencesOfString:@"-" withString:@""];
  
  return UUID;
}
  • 获取MAC地址
1
+ ( NSMutableString *) getMacAddr {
  kern_return_t kr;
  CFMutableDictionaryRef matchDict;
  io_iterator_t iterator;
  io_registry_entry_t entry;

  matchDict = IOServiceMatching("IOEthernetInterface");
  kr = IOServiceGetMatchingServices(kIOMasterPortDefault, matchDict, &iterator);

  NSDictionary *resultInfo = nil;

  NSMutableString *macAddrs = [[ NSMutableString alloc ] init];

  while ((entry = IOIteratorNext(iterator)) != 0)
  {
      CFMutableDictionaryRef properties=NULL;
      kr = IORegistryEntryCreateCFProperties(entry,
                                             &properties,
                                             kCFAllocatorDefault,
                                             kNilOptions);
      if (properties)
      {
          resultInfo = (__bridge_transfer NSDictionary *)properties;
          NSString *bsdName = [resultInfo objectForKey:@"BSD Name"];
          NSData *macData = [resultInfo objectForKey:@"IOMACAddress"];
          if (!macData)
          {
              continue;
          }

          NSMutableString *macAddress = [[NSMutableString alloc] init];
          const UInt8 *bytes = [macData bytes];
          for (int i=0; i<macData.length; i++)
          {
              [macAddress appendFormat:@"%02x",*(bytes+i)];
          }
          if (bsdName && macAddress)
          {
              [ macAddrs appendFormat:@"%@,", macAddress ];
          }
      }
  }
  IOObjectRelease(iterator);
  return macAddrs;
}