获取我Mac的计算机名称

Jon*_*an. 37 macos cocoa

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

Jon*_*an. 70

目标C.

我要找的名字是:

[[NSHost currentHost] localizedName];
Run Code Online (Sandbox Code Playgroud)

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

斯威夫特3

对于Swift> = 3使用.

if let deviceName = Host.current().localizedName {
   print(deviceName)
}
Run Code Online (Sandbox Code Playgroud)

  • 请注意[NSHost currentHost]执行阻塞网络查找.在慢速网络或断开连接的计算机上,它将停止您的应用程序,直到网络呼叫超时,除非您在后台线程上调用它. (11认同)
  • @dylan,是的swift 3:`Host.current().localizedName` (3认同)
  • 只需在注册服务时传递一个空字符串,就会自动使用您的本地化名称,这是Apple推荐的 (2认同)
  • 仅供参考,“NSHost”已在 macOS 12 Monterey 中弃用。 (2认同)

enn*_*ler 11

NSHost就是你想要的:

NSHost *host;

host = [NSHost currentHost];
[host name];
Run Code Online (Sandbox Code Playgroud)


Mar*_*ooi 9

我使用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];
}
Run Code Online (Sandbox Code Playgroud)

  • 最佳解决方案 AFAIK,不像“SCDynamicStoreCopyLocalHostName”,它将返回必要的“.local”后缀。 (2认同)

Dav*_*her 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];
Run Code Online (Sandbox Code Playgroud)

  • 请注意Apple注册Bonjour服务时不建议使用此方法.有关[技术问答QA1228](http://developer.apple.com/library/mac/#qa/qa1228/_index.html)的更多信息. (2认同)