2010-10-31 101 views

回答

61

目標C

我一直在尋找的名稱是:

[[NSHost currentHost] localizedName]; 

它返回 「喬納森的MacBook」,而不是「 Jonathans-Macbook「,或者只是name返回的」jonathans-macbook.local「。

夫特3

的SWIFT> = 3使用。

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

請注意[NSHost currentHost]執行阻止網絡查找。在慢速網絡或斷開連接的計算機上,它會停止您的應用程序,直到網絡調用超時,除非您在後臺線程上調用它。 – starkos 2011-11-14 12:23:19

+2

只需在註冊服務時傳遞一個空字符串,並按照Apple推薦的方式自動使用您的本地化名稱 – 2014-03-11 22:10:54

+0

有沒有辦法在Swift中編寫此代碼? – dylan 2016-10-14 14:42:19

10

NSHost是你想要的這裏:

NSHost *host; 

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

這會得到用戶友好的名稱(所以包括像空格和撇號之類的東西),或空間替換爲 - 和'刪除的dumber版本。 – 2010-10-31 17:39:24

+0

來自鏈接文檔:'可以是一個簡單的主機名,例如@「sales」,或者是一個完全合格的域名,例如@「sales.anycorp.com」。# – 2010-10-31 23:05:03

+0

不,我的意思是說「喬納森的MacBook 「或」Jonathans-Macbook「? – 2010-11-01 23:46:52

2

這裏有一個不阻止:

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

現在已棄用。 – Dev 2013-03-08 08:11:15

6

使用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]; 
+2

請注意Apple在註冊Bonjour服務時不建議使用此方法。更多信息請參見[技術問答QA1228](http://developer.apple.com/library/mac/#qa/qa1228/_index.html)。 – Dev 2013-03-08 08:14:52

+0

只是爲了澄清 - 'ComputerName'和'LocalHostName'在這裏是不同的。 Apple建議不要使用LocalHostName,因爲它具有比Bonjour服務所需更嚴格的限制 - 並且Bonjour自動註冊API使用ComputerName以及免費的一些重複數據刪除魔術。 – RJHunter 2018-02-03 07:14:26

6

我用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]; 
} 
+1

AFAIK的最佳解決方案,不像'SCDynamicStoreCopyLocalHostName',它會返回必要的「.local」後綴。 – 2016-07-13 03:34:13