NSNetService works fine, but can't get hostName, resolve causes error

前端 未结 3 498
旧巷少年郎
旧巷少年郎 2020-12-21 08:41

I\'m using Bonjour with an NSNetService to publish a server from my iPhone. It all works as expected, I can browse the pages I\'m serving etc. However, on the iPhone I want

3条回答
  •  Happy的楠姐
    2020-12-21 09:14

    The [[NSProcessInfo processInfo] hostName] method was not useful for me for two reasons:

    • If celular data is active, it returns some weird hostname at my provider's domain
    • If there's only WiFi, the host name is ok, but all lower case

    The following code from http://iphoneappcode.blogspot.com/2012/05/how-to-get-device-ipaddess-in-iphone.html worked best for me, always returning the local host name with sensitive case:

    + (NSString *) hostname
    {
        char baseHostName[256]; 
        int success = gethostname(baseHostName, 255);
        if (success != 0) return nil;
        baseHostName[255] = '\0';
    
    #if !TARGET_IPHONE_SIMULATOR
        return [NSString stringWithFormat:@"%s.local", baseHostName];
    #else
         return [NSString stringWithFormat:@"%s", baseHostName];
    #endif
    }
    

提交回复
热议问题