获取我Mac的计算机名称

时间:2010-10-31 12:48:08

标签: macos cocoa

如何在Mac上获取计算机的名称?我说的是与您在“软件”下的System Profiler中找到的名称相同的名称。

6 个答案:

答案 0 :(得分:69)

目标C

我要找的名字是:

[[NSHost currentHost] localizedName];

它返回“Jonathan的MacBook”而不是“Jonathans-Macbook”,或者只是name返回的“jonathans-macbook.local”。

Swift 3

对于Swift> = 3使用。

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

答案 1 :(得分:11)

NSHost就是你想要的:

NSHost *host;

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

答案 2 :(得分:7)

使用必须添加到项目中的 SystemConfiguration.framework

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

答案 3 :(得分:7)

我使用sysctlbyname(“kern.hostname”),它不会阻止。 请注意,我的帮助方法只应用于检索字符串属性,而不是整数。

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

答案 4 :(得分:2)

这是一个不阻止的:

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

答案 5 :(得分:1)

在终端中有:

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

然后在C语言中,您可以使用:

  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);
  }
相关问题