NSNetService Class Reference

Inherits from
Conforms to
Framework
/System/Library/Frameworks/Foundation.framework
Availability
Available in iOS 2.0 and later.
Declared in
NSNetServices.h
Companion guides
Related sample code

Overview

The NSNetService class represents a network service that your application publishes or uses as a client. This class and the NSNetServiceBrowser class use multicast DNS to convey information about network services to and from your application. The API of NSNetService provides a convenient way to publish the services offered by your application and to resolve the socket address for a service.

The types of services you access using NSNetService are the same types that you access directly using BSD sockets. HTTP and FTP are two services commonly provided by systems. (For a list of common services and the ports used by those services, see the file /etc/services.) Applications can also define their own custom services to provide specific data to clients.

You can use the NSNetService class as either a publisher of a service or as a client of a service. If your application publishes a service, your code must acquire a port and prepare a socket to communicate with clients. Once your socket is ready, you use the NSNetService class to notify clients that your service is ready. If your application is the client of a network service, you can either create an NSNetService object directly (if you know the exact host and port information) or you can use an NSNetServiceBrowser object to browse for services.

To publish a service, you must initialize your NSNetService object with the service name, domain, type, and port information. All of this information must be valid for the socket created by your application. Once initialized, you call the publish method to broadcast your service information out to the network.

When connecting to a service, you would normally use the NSNetServiceBrowser class to locate the service on the network and obtain the corresponding NSNetService object. Once you have the object, you proceed to call the resolveWithTimeout: method to verify that the service is available and ready for your application. If it is, the addresses property provides the socket information you can use to connect to the service.

The methods of NSNetService operate asynchronously so that your application is not impacted by the speed of the network. All information about a service is returned to your application through the NSNetService object’s delegate. You must provide a delegate object to respond to messages and to handle errors appropriately.

Tasks

Creating Network Services

Configuring Network Services

Managing Run Loops

Using Network Services

Obtaining the DNS Hostname

Properties

addresses

A read-only array containing NSData objects, each of which contains a socket address for the service. (read-only)

@property(readonly, copy) NSArray *addresses
Discussion

An array containing NSData objects, each of which contains a socket address for the service. Each NSData object in the returned array contains an appropriate sockaddr structure that you can use to connect to the socket. The exact type of this structure depends on the service to which you are connecting. If no addresses were resolved for the service, the returned array contains zero elements.

It is possible for a single service to resolve to more than one address or not resolve to any addresses. A service might resolve to multiple addresses if the computer publishing the service is currently multihoming.

Availability
  • Available in iOS 2.0 and later.
See Also
Declared In
NSNetServices.h

delegate

The delegate for the receiver.

@property(assign) id<NSNetServiceDelegate> delegate
Discussion

The delegate must conform to the NSNetServiceDelegate Protocol protocol, and is not retained.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSNetServices.h

domain

A string containing the domain for this service. (read-only)

@property(readonly, copy) NSString *domain
Discussion

This can be an explicit domain name or it can contain the generic local domain name, @"local." (note the trailing period, which indicates an absolute name).

This property’s value is set when the object is first initialized, whether by your code or by a browser object. See initWithDomain:type:name: for more information.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSNetServices.h

hostName

A string containing the DNS hostname for this service. (read-only)

@property(readonly, copy) NSString *hostName
Discussion

This value is nil until the service has been resolved (when addresses is non-nil).

Availability
  • Available in iOS 2.0 and later.
Declared In
NSNetServices.h

name

A string containing the name of this service. (read-only)

@property(readonly, copy) NSString *name
Discussion

This value is set when the object is first initialized, whether by your code or by a browser object. See initWithDomain:type:name: for more information.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSNetServices.h

port

The port on which the service is listening for connections. (read-only)

@property(readonly) NSInteger port
Discussion

If the object was initialized by calling initWithDomain:type:name:port: (whether by your code or by a browser object), then the value was set when the object was first initialized.

If the object was initialized by calling initWithDomain:type:name:, the value of this property is not valid (-1) until after the service has successfully been resolved (when addresses is non-nil).

Availability
  • Available in iOS 2.0 and later.
Declared In
NSNetServices.h

type

The type of the published service. (read-only)

@property(readonly, copy) NSString *type
Discussion

This value is set when the object is first initialized, whether by your code or by a browser object. See initWithDomain:type:name: for more information.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSNetServices.h

Class Methods

dataFromTXTRecordDictionary:

Returns an NSData object representing a TXT record formed from a given dictionary.

+ (NSData *)dataFromTXTRecordDictionary:(NSDictionary *)txtDictionary
Parameters
txtDictionary

A dictionary containing a TXT record.

Return Value

An NSData object representing TXT data formed from txtDictionary. Fails an assertion if txtDictionary cannot be represented as an NSData object.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSNetServices.h

dictionaryFromTXTRecordData:

Returns a dictionary representing a TXT record given as an NSData object.

+ (NSDictionary *)dictionaryFromTXTRecordData:(NSData *)txtData
Parameters
txtData

A data object encoding a TXT record.

Return Value

A dictionary representing txtData. The dictionary’s keys are NSString objects using UTF8 encoding. The values associated with all the dictionary’s keys are NSData objects that encapsulate strings or data.

Fails an assertion if txtData cannot be represented as an NSDictionary object.

Availability
  • Available in iOS 2.0 and later.
Related Sample Code
Declared In
NSNetServices.h

Instance Methods

getInputStream:outputStream:

Creates a pair of input and output streams for the receiver and returns a Boolean value that indicates whether they were retrieved successfully.

- (BOOL)getInputStream:(out NSInputStream **)inputStream outputStream:(out NSOutputStream **)outputStream
Parameters
inputStream

Upon return, the input stream for the receiver. Pass NULL if you do not need this stream.

outputStream

Upon return, the output stream for the receiver. Pass NULL if you do not need this stream.

Return Value

YES if the streams are created successfully, otherwise NO.

Discussion

After this method is called, no delegate callbacks are called by the receiver.

Availability
  • Available in iOS 2.0 and later.
Related Sample Code
Declared In
NSNetServices.h

initWithDomain:type:name:

Returns the receiver, initialized as a network service of a given type and sets the initial host information.

- (id)initWithDomain:(NSString *)domain type:(NSString *)type name:(NSString *)name
Parameters
domain

The domain for the service. To resolve in the default domains, pass in an empty string (@""). To limit resolution to the local domain, use @"local.".

If you are creating this object to resolve a service whose information your app stored previously, you should set this to the domain in which the service was originally discovered.

You can also use a NSNetServiceBrowser object to obtain a list of possible domains in which you can discover and resolve services.

type

The network service type.

type must contain both the service type and transport layer information. To ensure that the mDNS responder searches for services, as opposed to hosts, prefix both the service name and transport layer name with an underscore character (“_”). For example, to search for an HTTP service on TCP, you would use the type string "_http._tcp.". Note that the period character at the end of the string, which indicates that the domain name is an absolute name, is required.

name

The name of the service to resolve.

Return Value

The receiver, initialized as a network service named name of type type in the domain domain.

Discussion

This method is the appropriate initializer to use to resolve a service—to publish a service, use initWithDomain:type:name:port:.

If you know the values for domain, type, and name of the service you wish to connect to, you can create an NSNetService object using this initializer and call resolveWithTimeout: on the result.

You cannot use this initializer to publish a service. This initializer passes an invalid port number to the designated initializer, which prevents the service from being registered. Calling publish on an NSNetService object initialized with this method generates a call to your delegate’s netService:didNotPublish: method with an NSNetServicesBadArgumentError error.

Availability
  • Available in iOS 2.0 and later.
Related Sample Code
Declared In
NSNetServices.h

initWithDomain:type:name:port:

Initializes the receiver for publishing a network service of type type at the socket location specified by domain, name, and port.

- (id)initWithDomain:(NSString *)domain type:(NSString *)type name:(NSString *)name port:(int)port
Parameters
domain

The domain for the service. To use the default registration domains, pass in an empty string (@""). To limit registration to the local domain, use @"local.".

You can also use a NSNetServiceBrowser object to obtain a list of possible domains in which you can publish your service.

type

The network service type.

type must contain both the service type and transport layer information. To ensure that the mDNS responder searches for services, as opposed to hosts, prefix both the service name and transport layer name with an underscore character (“_”). For example, to search for an HTTP service on TCP, you would use the type string "_http._tcp.". Note that the period character at the end of the string, which indicates that the domain name is an absolute name, is required.

name

The name by which the service is identified to the network. The name must be unique. If you pass the empty string (@""), the system automatically advertises your service using the computer name as the service name.

port

The port on which the service is published.

If you specify the NSNetServiceListenForConnections flag, you may pass zero (0), in which case the service automatically allocates an arbitrary (ephemeral) port for your service. When the delegate’s netServiceDidPublish: is called, you can determine the actual port chosen by calling the service object’s Backward Compatibility Note method or accessing the corresponding property.

If your app is listening for connections on its own, the value of port must be a port number acquired by your application for the service.

Discussion

You use this method to create a service that you wish to publish on the network. Although you can also use this method to create a service you wish to resolve on the network, it is generally more appropriate to use the initWithDomain:type:name: method instead.

When publishing a service, you must provide valid arguments in order to advertise your service correctly. If the host computer has access to multiple registration domains, you must create separate NSNetService objects for each domain. If you attempt to publish in a domain for which you do not have registration authority, your request may be denied.

It is acceptable to use an empty string for the domain argument when publishing or browsing a service, but do not rely on this for resolution.

This method is the designated initializer.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSNetServices.h

publish

Attempts to advertise the receiver’s on the network.

- (void)publish
Discussion

This method returns immediately, with success or failure indicated by the callbacks to the delegate. This is equivalent to calling publishWithOptions: with the default options (0).

Availability
  • Available in iOS 2.0 and later.
See Also
Declared In
NSNetServices.h

publishWithOptions:

Attempts to advertise the receiver on the network, with the given options.

- (void)publishWithOptions:(NSNetServiceOptions)serviceOptions
Parameters
serviceOptions

Options for the receiver. The supported options are described in NSNetServiceOptions.

Discussion

This method returns immediately, with success or failure indicated by the callbacks to the delegate.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSNetServices.h

removeFromRunLoop:forMode:

Removes the service from the given run loop for a given mode.

- (void)removeFromRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode
Parameters
aRunLoop

The run loop from which to remove the receiver.

mode

The run loop mode from which to remove the receiver. Possible values for mode are discussed in the "Constants" section of NSRunLoop.

Discussion

You can use this method in conjunction with scheduleInRunLoop:forMode: to transfer the service to a different run loop. Although it is possible to remove an NSNetService object completely from any run loop and then attempt actions on it, it is an error to do so.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSNetServices.h

resolveWithTimeout:

Starts a resolve process of a finite duration for the receiver.

- (void)resolveWithTimeout:(NSTimeInterval)timeout
Parameters
timeout

The maximum number of seconds to attempt a resolve. A value of 0.0 indicates no timeout and a resolve process of indefinite duration.

Discussion

If the resolve succeeds before the timeout period lapses, the receiver sends netServiceDidResolveAddress: to the delegate. Otherwise, the receiver sends netService:didNotResolve: to the delegate.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSNetServices.h

scheduleInRunLoop:forMode:

Adds the service to the specified run loop.

- (void)scheduleInRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode
Parameters
aRunLoop

The run loop to which to add the receiver.

mode

The run loop mode to which to add the receiver. Possible values for mode are discussed in the "Constants" section of NSRunLoop.

Discussion

You can use this method in conjunction with removeFromRunLoop:forMode: to transfer a service to a different run loop. You should not attempt to run a service on multiple run loops.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSNetServices.h

setTXTRecordData:

Sets the TXT record for the receiver, and returns a Boolean value that indicates whether the operation was successful.

- (BOOL)setTXTRecordData:(NSData *)recordData
Parameters
recordData

The TXT record for the receiver.

Return Value

YES if recordData is successfully set as the TXT record, otherwise NO.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSNetServices.h

startMonitoring

Starts the monitoring of TXT-record updates for the receiver.

- (void)startMonitoring
Discussion

The delegate must implement netService:didUpdateTXTRecordData:, which is called when the TXT record for the receiver is updated.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSNetServices.h

stop

Halts a currently running attempt to publish or resolve a service.

- (void)stop
Discussion

This method results in the sending of a netServiceDidStop: message to the delegate.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSNetServices.h

stopMonitoring

Stops the monitoring of TXT-record updates for the receiver.

- (void)stopMonitoring
Availability
  • Available in iOS 2.0 and later.
Declared In
NSNetServices.h

TXTRecordData

Returns the TXT record for the receiver.

- (NSData *)TXTRecordData
Availability
  • Available in iOS 2.0 and later.
Related Sample Code
Declared In
NSNetServices.h

Constants

NSNetServices Errors

If an error occurs, the delegate error-handling methods return a dictionary with the following keys.

extern NSString *NSNetServicesErrorCode;
extern NSString *NSNetServicesErrorDomain;
Constants
NSNetServicesErrorCode

This key identifies the error that occurred during the most recent operation.

Available in iOS 2.0 and later.

Declared in NSNetServices.h.

NSNetServicesErrorDomain

This key identifies the originator of the error, which is either the NSNetService object or the mach network layer. For most errors, you should not need the value provided by this key.

Available in iOS 2.0 and later.

Declared in NSNetServices.h.

Declared In
NSNetServices.h

NSNetServicesError

These constants identify errors that can occur when accessing net services.

typedef enum {
   NSNetServicesUnknownError = -72000,
   NSNetServicesCollisionError = -72001,
   NSNetServicesNotFoundError    = -72002,
   NSNetServicesActivityInProgress = -72003,
   NSNetServicesBadArgumentError = -72004,
   NSNetServicesCancelledError = -72005,
   NSNetServicesInvalidError = -72006,
   NSNetServicesTimeoutError = -72007,
} NSNetServicesError;
Constants
NSNetServicesUnknownError

An unknown error occurred.

Available in iOS 2.0 and later.

Declared in NSNetServices.h.

NSNetServicesCollisionError

The service could not be published because the name is already in use. The name could be in use locally or on another system.

Available in iOS 2.0 and later.

Declared in NSNetServices.h.

NSNetServicesNotFoundError

The service could not be found on the network.

Available in iOS 2.0 and later.

Declared in NSNetServices.h.

NSNetServicesActivityInProgress

The net service cannot process the request at this time. No additional information about the network state is known.

Available in iOS 2.0 and later.

Declared in NSNetServices.h.

NSNetServicesBadArgumentError

An invalid argument was used when creating the NSNetService object.

Available in iOS 2.0 and later.

Declared in NSNetServices.h.

NSNetServicesCancelledError

The client canceled the action.

Available in iOS 2.0 and later.

Declared in NSNetServices.h.

NSNetServicesInvalidError

The net service was improperly configured.

Available in iOS 2.0 and later.

Declared in NSNetServices.h.

NSNetServicesTimeoutError

The net service has timed out.

Available in iOS 2.0 and later.

Declared in NSNetServices.h.

Declared In
NSNetServices.h

NSNetServiceOptions

These constants specify options for a network service.

enum {
   NSNetServiceNoAutoRename = 1 << 0
   NSNetServiceListenForConnections = 1UL << 1
};
typedef NSUInteger NSNetServiceOptions;
Constants
NSNetServiceNoAutoRename

Specifies that the network service should not rename itself in the event of a name collision.

Available in iOS 2.0 and later.

Declared in NSNetServices.h.

NSNetServiceListenForConnections

Specifies that a TCP listener should be started for both IPv4 and IPv6 on the port specified by this service. If the listening port can't be opened, the service calls its delegate’s netService:didNotPublish: method to report the error.

The listener supports only TCP connections. If the service’s type does not end with _tcp, publication fails with NSNetServicesBadArgumentError.

Whenever a client connects to the listening socket, the service calls its delegate’s netService:didAcceptConnectionWithInputStream:outputStream: method with a pair of NSStream objects.

Available in iOS 7.0 and later.

Declared in NSNetServices.h.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSNetServices.h