代码之家  ›  专栏  ›  技术社区  ›  Jonathan.

获取我的Mac电脑名

  •  36
  • Jonathan.  · 技术社区  · 14 年前

    我怎样才能在Mac电脑上找到电脑的名字?我说的名字和你在“软件”下的系统剖析器中找到的名字一样。

    6 回复  |  直到 11 年前
        1
  •  71
  •   Saqib Omer Dasoga    8 年前

    目标C

    我要找的名字是:

    [[NSHost currentHost] localizedName];
    

    它返回“Jonathan s MacBook”而不是“Jonathans MacBook”或“Jonathans MacBook.local”,这只是 name 返回。

    用于Swift>=3用途。

    if let deviceName = Host.current().localizedName {
       print(deviceName)
    }
    
        2
  •  11
  •   ennuikiller    14 年前

    NSHost

    NSHost *host;
    
    host = [NSHost currentHost];
    [host name];
    
        3
  •  9
  •   Mark de Rooi    10 年前

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

    #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
  •  7
  •   Dave    13 年前

    系统配置.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];
    
        5
  •  2
  •   J. Perkins    13 年前

    NSString* name = [(NSString*)CSCopyMachineName() autorelease];
    
        6
  •  2
  •   antoine    7 年前

    在终端中,您可以使用:

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

      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);
      }