Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.1k views
in Technique[技术] by (71.8m points)

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

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 to display the host name (i.e. the URL, like "myDevice.local."), so that one can also enter the address manually in a browser (useful for clients missing a bonjour discovery service). My understanding is that calling the method [myNetService hostName] should give me that address. However, this call always returns nil. I read on some forum that I first should resolve the service, however both [myNetService resolve] and [myNetService resolveWithTimeout:10] call the delegate method

- (void)netService:(NSNetService *)sender didNotResolve:(NSDictionary *)errorDict;

with the error

{
    NSNetServicesErrorCode = -72003;
    NSNetServicesErrorDomain = 10;
}

which apparently means that it is already resolved. Again, all this is happening while i can use the service. Also I can get the port, the domain, and the type of the service. The only other strange thing is that the call [myNetService addresses] returns an empty array.

I'm using SDK 3.1.3. Does anybody have an idea what I could be doing wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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] = '';

#if !TARGET_IPHONE_SIMULATOR
    return [NSString stringWithFormat:@"%s.local", baseHostName];
#else
     return [NSString stringWithFormat:@"%s", baseHostName];
#endif
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...