开发者

Get my Mac's computer name

How can I get the computer's name on a Mac? I'm talking 开发者_JAVA技巧about the same name as the one you can find in System Profiler under "Software".


Objective C

The name I was looking for is:

[[NSHost currentHost] localizedName];

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

Swift 3

For Swift >= 3 use.

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


I use sysctlbyname("kern.hostname"), which does not block. Please note that my helper method should only be used to retrieve string 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];
}


NSHost is what you want here:

NSHost *host;

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


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];


in terminal you have it with :

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

then in C 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);
  }


Here's one that doesn't block:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜