6

我想知道是否可以获取我的 iOS 应用当前正在使用的播放设备的 IP 地址。

要么是那个,要么是网络上所有支持播放的设备的 IP 地址。

先感谢您!

编辑:虽然我现在有一个公认的答案,但我很想知道如何获取当前播放的播放设备的 IP。

4

1 回答 1

7

您必须使用 NSNetServiceBrowser 来使用该协议搜索设备。我对打印机做了同样的事情,我的代码如下所示:

    _netServiceBrowser= [[NSNetServiceBrowser alloc] init];
    _netServiceBrowser.delegate= self;
    [_netServiceBrowser searchForServicesOfType:@"_pdl-datastream._tcp" inDomain:@"local."];

您必须更改@"_pdl-datastream._tcp"要搜索的协议,您可以在此处找到协议列表:http: //developer.apple.com/library/mac/#qa/qa1312/_index.html

之后,您必须编写协议的功能:

#pragma mark - NSNetServiceBrowserDelegate

-(void)netServiceBrowserWillSearch:(NSNetServiceBrowser *)aNetServiceBrowser{
     //prepare the start of the search
}

-(void)netServiceBrowser:(NSNetServiceBrowser *)aNetServiceBrowser didFindService:(NSNetService *)aNetService moreComing:(BOOL)moreComing{
//Find a service, remember that after that you have to resolve the service to know the address

[_printers addObject:aNetService];
aNetService.delegate=self;
[aNetService resolveWithTimeout:5.0];

//More coming says if it has find more services, in case of more service are in queue wait to reload your interface
if (!moreComing) {
    [self.tableView reloadData];   
}
}

-(void)netServiceBrowser:(NSNetServiceBrowser *)aNetServiceBrowser didNotSearch:(NSDictionary *)errorDict{
//Do what you want in case of error
}

-(void)netServiceBrowserDidStopSearch:(NSNetServiceBrowser *)aNetServiceBrowser{

//End search!
}

- (NSString *)getStringFromAddressData:(NSData *)dataIn {
//Function to parse address from NSData
struct sockaddr_in  *socketAddress = nil;
NSString            *ipString = nil;

socketAddress = (struct sockaddr_in *)[dataIn bytes];
ipString = [NSString stringWithFormat: @"%s",
            inet_ntoa(socketAddress->sin_addr)];  ///problem here
return ipString;
}

- (void)netServiceDidResolveAddress:(NSNetService *)sender
{
//delegate of NSNetService resolution process
[_addresses addObject:[self getStringFromAddressData:[sender.addresses objectAtIndex:0]]];
[self.tableView reloadData];
}

一个有用的网站:http: //www.macresearch.org/cocoa-scientists-part-xxviii-bonjour-and-how-do-you-do

希望对你有帮助

于 2012-04-11T09:34:55.590 回答