tags:

views:

2194

answers:

1

Excuse my iPhone/Objective-C newbie status please!

I've found my HTTP server using NSNetServiceBrowser, but now I just want the IP address and port of the service found.

I've got something like the following in my delegate method:

NSNetService* server = [serverBrowser.servers objectAtIndex:0];

NSString            *name = nil;
NSData              *address = nil;
struct sockaddr_in  *socketAddress = nil;
NSString            *ipString = nil;
int                 port;
uint                 i;
for (i = 0; i < [[server addresses] count]; i++)
{
    name = [server name];
    address = [[server addresses] objectAtIndex:i];
    socketAddress = (struct sockaddr_in *)
    [address bytes];
    ipString = [NSString stringWithFormat: @"%s",
                inet_ntoa (socketAddress->sin_addr)];
    port = socketAddress->sin_port;
    NSLog(@"Server found is %s %d",ipString,port);
}

but the for loop is never entered, even though the delegate is called. Any ideas? Thanks!

+5  A: 

The NSNetService you get back in the callback isn't ready to be used. You have to call the following method to get addresses for it:

- (void)resolveWithTimeout:(NSTimeInterval)timeout;

Implement the NSNetService delegate method to find out when it resolves:

- (void)netServiceDidResolveAddress:(NSNetService *)sender;

At that point, there should be at least one address in the service.

Also, take care to read the documentation and the header file carefully! There is some complexity to the issue here that I've glossed over.

Andrew Pouliot
Thanks, exactly what I needed.
NiKUMAN