NSNetServices

From GNUstepWiki
Revision as of 10:04, 23 January 2007 by Cbv (talk | contribs) (added snippet)
Jump to navigation Jump to search
This article or section is a stub (i.e., in need of additional material).
You can help us by expanding it


NSNetService lets you publish a network service in a domain using multicast DNS. Additionally, it lets you resolve a network service that was discovered by NSNetServiceBrowser.

Code chunks

How to resolve an address

When you browse for a service, your delegate will eventually receive a -netServiceBrowser:didFindService:moreComing: message.

 - (void)netServiceBrowser: (NSNetServiceBrowser *) aNetServiceBrowser 
            didFindService: (NSNetService *) aNetService 
                moreComing: (BOOL) moreComing
 {
   [aNetService setDelegate: self];
   [aNetService resolve];
 }

When you send -resolve this will eventually result in a message sent to the delegate:

 - (void) netServiceDidResolveAddress: (NSNetService *) sender
 {
   NSString           *name = nil;
   NSData             *address = nil;
   struct sockaddr_in *socketAddress = nil;
   NSString           *ipString = nil;
   int                port, i = 0;
   
   // A service is published on ALL network addresses,
   // so -addresses may contain more than one IP
   
   for( ; i < [[sender addresses] count]; i++ )
   {
     name = [sender name];
     address = [[sender addresses] objectAtIndex: i];
     
     // IPs are sockaddr_in structures encapsulated in NSData...
     
     socketAddress = (struct sockaddr_in *) [address bytes];
     ipString = [NSString stringWithFormat: @"%s", inet_ntoa(socketAddress->sin_addr)];
     port = socketAddress->sin_port;
     [...]
   }
 }

After you have the name, IP and port you are ready to use that information. You will probably store the information in an array so you can access it any time you need it.