Retrieving network address information

Most applications that communicate over a network will eventually need to know the information from the available network interfaces of the device they are running on. This recipe will show you how to retrieve the network addresses for all the active network interfaces on the device.

This recipe will use the NSHost class to retrieve a list of addresses on your local device. While NSHost is available on iOS, it is a private (undocumented) class. It is also noted on a number of forum posts that Apple has rejected iOS apps for using NSHost. If you need to retrieve network address information within an iOS application, it is recommended that you use the Retrieving network address information recipe from Chapter 1, BSD Socket Library, in this book, and not the NSHost class described in this recipe.

Getting ready

This recipe is compatible with both iOS and OS X, but it is recommended that you do not use NSHost on the iOS platform. No extra frameworks or libraries are required.

How to do it...

We retrieve the network address information in the following manner:

  1. Let's retrieve the network address information of our local device:
    NSHost* myHost =[NSHost currentHost];
    if (myHost)
    {
      NSArray *addresses = [myHost addresses];
      
      for (NSString *address in addresses) {
        NSLog(@"%@", address );
      }
    }
  2. To create an NSHost object, you will want to use one of the following three class methods (do not use alloc and init to create the object):
    • currentHost: It returns an NSHost object, which represents the host the process is currently running on.
    • hostWithAddress: It returns an NSHost object representing the host defined by the supplied IP address. You would use this method by supplying the address as an NSString object; for example, [NSHost hostWithAddress:@"83.166.169.231"].
    • hostWithName: It returns an NSHost object representing the host defined by the supplied hostname. You would use this method by supplying the address as an NSString object; for example, [NSHost hostWithName:@"www.packtpub.com"].

For our recipe, we are looking for the network address information of the localhost; therefore, we will use the currentHost method to create our NSHost object.

How it works…

The NSHost class provides various methods that can be used to access the name and address information for a host. An NSHost object will represent an individual host and will contain all the network addresses and names associated with that host.

Note

While NSHost is much easier to use than the Retrieving network address information recipe in Chapter 1, BSD Socket Library, NSHost is an undocumented (private) class for iOS. It could be changed or removed anytime from the iOS SDK. Apple could also reject your iOS app for using NSHost; therefore, it should only be used in OS X applications.