如何在 Mac 上获取计算机的名称?我说的是与您可以在“软件”下的系统分析器中找到的名称相同的名称。
目标C
我要找的名字是:
[[NSHost currentHost] localizedName];
它返回“Jonathan's MacBook”而不是“Jonathans-Macbook”或“jonathans-macbook.local”,后者只是
name
返回。
斯威夫特3
对于 Swift >= 3 使用。
if let deviceName = Host.current().localizedName {
print(deviceName)
}
我使用 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];
}
NSHost 就是你想要的:
NSHost *host;
host = [NSHost currentHost];
[host name];
使用 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];
在终端中你可以使用:
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);
}
这是一个不会阻塞的:
NSString* name = [(NSString*)CSCopyMachineName() autorelease];
由于
Host
将在 macOS 的未来版本中被弃用,请尝试:
let computerName = ProcessInfo.processInfo.hostName