Apple Bonjour: how can I tell which published service is my own?
I have two iOS devices开发者_如何学编程 finding each other successfully using the Bonjour API, but since they are both simultaneously publishing and browsing, they also see themselves appearing in the list of available services. There must be some bit of information each endpoint can use to determine that a service is their own and exclude it from their list... I'm sure I just missed it somewhere - any ideas?
I have used the examples from the docs with a few small changes.
mDNS doesn't make any distinction between device boundaries- every mDNS resolver on the link-local network listens for all multicast packets sent to 224.0.0.251
by default regardless of origin. Think of it as a glorified short-wave radio. Well, kind of.
That means when you browse for services, NSNetServiceBrowser doesn't discriminate between hosts (and there are times when I've found that to be a useful feature in server-side applications).
I'd suggest the easiest way to ignore your own services is to check that the hostname
of the NSNetService
object returned in the netServiceBrowser:didFindService:moreComing:
callback isn't yours before doing whatever you need to do with it.
I am using IOS 8.1 and I had the same question. I ended up comparing the name of each service returned by didFindService against the name of the local NSNetService representing my bonjour server.
Based on what I see debugging my app, the hostname of each NSNetService is nil until the service is resolved. In my case I did not call resolveWithTimeout inside didFindService because I guess it would take too long to display the data.
As hinted by the accepted answer, compare the NSNetService
name to the device name:
- (void)netServiceBrowser:(NSNetServiceBrowser *)aNetServiceBrowser didFindService:(NSNetService *)aNetService moreComing:(BOOL)moreComing
{
// Ignore the local device if specified
if ([aNetService.name isEqualToString:UIDevice.currentDevice.name])
{
NSLog(@"NETSERVICE: Ignoring NetService for self: '%@'", aNetService.name);
}
else
{
...
}
// If that's it then stop the browser (it's manually controlled)
if (!moreComing) {
[_netBrowser stop];
}
}
精彩评论