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)
enn*_*ler 11
NSHost就是你想要的:
NSHost *host;
host = [NSHost currentHost];
[host name];
Run Code Online (Sandbox Code Playgroud)
我使用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)
使用必须添加到项目中的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)
归档时间: |
|
查看次数: |
19681 次 |
最近记录: |