The Foundation Framework includes various APIs to support network services. In the next few chapters, you’ll learn about APIs used to access network host information, and explore how to utilize the Bonjour network protocol to publish and discover network services.
NSHost
The NSHost class contains methods to access information for a network host, which is a collection of network names and addresses for a computer or device connected to a network. An NSHost object represents an individual network host. Its methods can be used to look up the network name and address information for the host or other objects on a network. The code in Listing 11-1 uses the NSHost currentHost and name methods to retrieve the NSHost object for the host the program is running on, and then logs the host name to the console.
Listing 11-1. Retrieving the Network Host Name Using NSHost
NSHost myHost = [NSHost currentHost];
NSLog(@"Host name is %@", [myHost name]);
Listing 11-2 uses the NSHost hostWithName: and address methods to create an NSHost object with the domain name www.apress.com , and then logs the host address to the console.
Listing 11-2. Retrieving a Host Address Using NSHost
NSHost *apress = [NSHost hostWithName:@"www.apress.com
"];
NSLog(@"Apress host address is %@", [apress address]);
Bonjour is a protocol that automatically creates a functional IP network without the need for configuration or manual intervention, also known as zero configuration networking. Bonjour is designed to enable devices, such as computers and printers, to connect to a network automatically. It performs a variety of functions, including service discovery, address assignment, and hostname resolution.
The NSNetService and NSNetServiceBrowser classes provide functionality to manage Bonjour network services. The NSNetService class represents a network service that an application publishes or uses as a client. A service can be either a local service that your application is publishing or a remote service that your application wants to use. The NSNetServiceBrowser class is used to find published network services. Each class must provide a delegate object that performs processing upon completion of method invocation. The methods for each class are invoked asynchronously and performed within a run loop. Later in this chapter, you’ll learn how to use the NSRunLoop class to manage run loops.