[ACCEPTED]-Get my Mac's computer name-cocoa

Accepted answer
Score: 81

Objective C

The name I was looking for is:

[[NSHost currentHost] localizedName];

It returns 3 "Jonathan's MacBook" rather than "Jonathans-Macbook", or 2 "jonathans-macbook.local" which just name returns.

Swift 3

For 1 Swift >= 3 use.

if let deviceName = Host.current().localizedName {
   print(deviceName)
}
Score: 13

I use sysctlbyname("kern.hostname"), which 3 does not block. Please note that my helper 2 method should only be used to retrieve string 1 attributes, not integers.

#include <sys/sysctl.h>

- (NSString*) systemInfoString:(const char*)attributeName
{
    size_t size;
    sysctlbyname(attributeName, NULL, &size, NULL, 0); // Get the size of the data.
    char* attributeValue = malloc(size);
    int err = sysctlbyname(attributeName, attributeValue, &size, NULL, 0);
    if (err != 0) {
        NSLog(@"sysctlbyname(%s) failed: %s", attributeName, strerror(errno));
        free(attributeValue);
        return nil;
    }
    NSString* vs = [NSString stringWithUTF8String:attributeValue];
    free(attributeValue);
    return vs;
}

- (NSString*) hostName
{
    NSArray* components = [[self systemInfoString:"kern.hostname"] componentsSeparatedByString:@"."];
    return [components][0];
}
Score: 12

NSHost is what you want here:

NSHost *host;

host = [NSHost currentHost];
[host name];

0

Score: 7

Using the SystemConfiguration.framework, which you must add to your project:

#include <SystemConfiguration/SystemConfiguration.h>

...

// Returns NULL/nil if no computer name set, or error occurred. OSX 10.1+
NSString *computerName = [(NSString *)SCDynamicStoreCopyComputerName(NULL, NULL) autorelease];

// Returns NULL/nil if no local hostname set, or error occurred. OSX 10.2+
NSString *localHostname = [(NSString *)SCDynamicStoreCopyLocalHostName(NULL) autorelease];

0

Score: 3

in terminal you have it with :

system_profiler SPSoftwareDataType | grep "Computer Name" | cut -d: -f2 | tr -d [:space:]

then in C 1 you can get it with :

  FILE* stream = popen("system_profiler SPSoftwareDataType | grep \"Computer Name\" | cut -d: -f2 | tr -d [:space:]", "r");
  ostringstream hoststream;

  while(!feof(stream) && !ferror(stream))
  {
      char buf[128];
      int byteRead = fread( buf, 1, 128, stream);
      hoststream.write(buf, byteRead);
  }
Score: 2

Here's one that doesn't block:

NSString* name = [(NSString*)CSCopyMachineName() autorelease];

0

More Related questions