OS X Computer Name and Local Host Name

On OS X your computer name and local host name are stored in a preference file - accessible via SCPreferences. In a recent project I needed these values. The following two Objective-C functions are what I'm using. The excessive error reporting was really only necessary while I was testing these; feel free to remove it.

The SCPreferences documentation suggests locking the file before reading any values so as to avoid the possibility of reading old data. I never could get the file to lock, and I suspect it's a root-only feature.

ARC-dependent, of course.


+ (NSString *)computerName
{
  SCPreferencesRef prefs = SCPreferencesCreate(nil, CFSTR("com.super-pigeon.SuperPigeonMac"), nil);
  
  if (!prefs) {
    NSLog(@"%s.. ERROR: failed to SPPreferencesCreate()", __PRETTY_FUNCTION__);
    return nil;
  }
  
  NSDictionary *system = (__bridge NSDictionary *)SCPreferencesGetValue(prefs, kSCPrefSystem);
  
  if (!system) {
    NSLog(@"%s.. ERROR: failed to SCPreferencesGetValue(kSCPrefSystem)", __PRETTY_FUNCTION__);
    return nil;
  }
  
  NSDictionary *system2 = [system objectForKey:@"System"];
  
  if (!system2) {
    NSLog(@"%s.. ERROR: failed to get 'System'", __PRETTY_FUNCTION__);
    return nil;
  }
  
  NSString *computerName = [system2 objectForKey:@"ComputerName"];
  
  if (!computerName) {
    NSLog(@"%s.. failed to get 'ComputerName'", __PRETTY_FUNCTION__);
    return nil;
  }
  
  NSString *value = [NSString stringWithString:computerName];
  
  CFRelease(prefs);
  
  return value;
}

+ (NSString *)localHostName
{
  SCPreferencesRef prefs = SCPreferencesCreate(nil, CFSTR("com.super-pigeon.SuperPigeonMac"), nil);
  
  if (!prefs) {
    NSLog(@"%s.. ERROR: failed to SPPreferencesCreate()", __PRETTY_FUNCTION__);
    return nil;
  }
  
  NSDictionary *system = (__bridge NSDictionary *)SCPreferencesGetValue(prefs, kSCPrefSystem);
  
  if (!system) {
    NSLog(@"%s.. ERROR: failed to SCPreferencesGetValue(kSCPrefSystem)", __PRETTY_FUNCTION__);
    return nil;
  }
  
  NSDictionary *network = [system objectForKey:@"Network"];
  
  if (!network) {
    NSLog(@"%s.. ERROR: failed to get 'Network'", __PRETTY_FUNCTION__);
    return nil;
  }
  
  NSDictionary *hostNames = [network objectForKey:@"HostNames"];
  
  if (!hostNames) {
    NSLog(@"%s.. failed to get 'HostNames'", __PRETTY_FUNCTION__);
    return nil;
  }
  
  NSString *localHostName = [hostNames objectForKey:@"LocalHostName"];
  
  if (!localHostName) {
    NSLog(@"%s.. failed to get 'LocalHostName'", __PRETTY_FUNCTION__);
    return nil;
  }
  
  NSString *value = [localHostName stringByAppendingString:@".local"];
  
  CFRelease(prefs);
  
  return value;
}

Subscribe to A garage sale for your mind

Don’t miss out on the latest posts. Sign up now to get access to the library of members-only posts.
[email protected]
Subscribe