Just An Application

November 20, 2013

Service Discovery In Android And iOS: Part Eight – iOS Take Four

If DNSServiceBrowse and friends are not to your liking there is always the function DNSServiceQueryRecord which enables us to obtain DNS records directly.

1.0 DNSServiceQueryRecord

The DNSServiceQueryRecord function declaration follows the common function pattern and looks like this

    DNSServiceErrorType DNSServiceQueryRecord(
                            DNSServiceRef*             sdRef,
                            DNSServiceFlags            flags,
                            uint32_t                   interfaceIndex,
                            const char*                fullname,
                            uint16_t                   rrtype,
                            uint16_t                   rrclass,
                            DNSServiceQueryRecordReply callBack,
                            void*                      context);

The fullname should be the absolute name of the node for which the record or records are being requested.

The rrtype should be the type of the record or records being requested.

The rrclass should be the class of the record or records being requested.

If the kDNSServiceFlagsTimeout bit is set in the flags argument then the function will timeout after a system dependent amount of time.

2.0 The DNSServiceQueryRecord Callback Function

The callback function will be invoked

  • once for each record that is received in response to the query

  • once for each record that is received in response to the query that subsequently expires

  • if an error occurs

  • if a timeout occurs

3.0 DNSServiceQueryRecordReply

The DNSServiceQueryRecordReply function type declaration follows the common function type pattern and looks like this

    typedef void (*DNSServiceQueryRecordReply)(
                       DNSServiceRef       sdRef,
                       DNSServiceFlags     flags,
                       uint32_t            interfaceIndex,
                       DNSServiceErrorType errorCode,
                       const char*         fullname,
                       uint16_t            rrtype,
                       uint16_t            rrclass,
                       uint16_t            rdlen,
                       const void*         rdata,
                       uint32_t            ttl,
                       void*               context);

When a function of this type is invoked, then, if the errorCode argument is kDNSServiceErr_NoError

  • fullname is the absolute name of the node with the record is associated

  • rrtype is the type of the record

  • rrclass is the class of the record.

  • rdlen is the length of the record data

  • rdate is the record data

  • ttl is the time in seconds for which the record is valid

The flags argument will have the kDNSServiceFlagsAdd bit set if the callback is being invoked when a record is received in response to the query.

If kDNSServiceFlagsAdd bit is clear then callback is being invoked because the record has expired,
in which case the ttl argument will be 0.

If a timeout occurs the value of the errorCode argument will be kDNSServiceErr_Timeout.

3.0 The Query Class

We can encapsulate the call to DNSServiceQueryRecord and its associated callback function in a class
like so

    //
    //  Query.m
    //  XperTakeFour
    //
    //  Created by Simon Lewis on 08/11/2013.
    //  Copyright (c) 2013 Simon Lewis. All rights reserved.
    //
        
    #import <dns_sd.h>
        
    #import "QueryDelegate.h"
    #import "Record.h"
        
    #import "Query.h"
        
    @interface Query()
        
    @property NSString* name;
    @property uint16_t  type;
    @property uint16_t class;
        
    - (void)record:(const Record*)theRecord onInterface:(uint32_t)theIndex;
        
    - (void)recordExpired:(const Record*)theRecord;
        
    - (void)failed:(DNSServiceErrorType)theName;
        
    @end
        
    @implementation Query
    {
        DNSServiceRef   ref;
    }
        
    - (Query*)init:(NSString*)theName type:(uint16_t)theType class:(uint16_t)theClass
    {
        self = [super init];
        if (self != nil)
        {
            self.name  = theName;
            self.type  = theType;
            self.class = theClass;
        }
        return self;
    }
    
    static void queryCallback(
                    DNSServiceRef       sdRef,
                    DNSServiceFlags     theFlags,
                    uint32_t            theInterfaceIndex,
                    DNSServiceErrorType theErrorCode,
                    const char*         theName,
                    uint16_t            theType,
                    uint16_t            theClass,
                    uint16_t            theDataLength,
                    const void*         theData,
                    uint32_t           theTTL,
                    void*               theContext)
    {
        NSLog(@"queryCallback: flags == %d error code == %d", theFlags, theErrorCode);
        
        if (theErrorCode != kDNSServiceErr_NoError)
        {
            [(__bridge Query*)theContext failed:theErrorCode];
        }
        else
        {
            NSLog(@"theName == %s theType == %u", theName, theType);
        
            Record rr = {
                            theName,
                            theType,
                            theClass,
                            theTTL,
                            theDataLength,
                            theData
                        };
        
            if ((theFlags & kDNSServiceFlagsAdd) != 0)
            {
                [(__bridge Query*)theContext record:&rr onInterface:theInterfaceIndex];
            }
            else
            {
                [(__bridge Query*)theContext recordExpired:&rr];
            }
        }
    }
        
        
    - (void)start:(DNSServiceRef)theServiceRef interface:(uint32_t)theInterfaceIndex timeout:(BOOL)timeout
    {
        ref = theServiceRef;
        
        DNSServiceErrorType error;
        DNSServiceFlags     flags;
        
        flags = kDNSServiceFlagsShareConnection;
        if (timeout)
        {
            flags |= kDNSServiceFlagsTimeout;
        }
        error = DNSServiceQueryRecord(
                    &ref,
                    flags,
                    theInterfaceIndex,
                    [self.name UTF8String],
                    self.type,
                    self.class,
                    queryCallback,
                    (__bridge void*)self);
        if (error != kDNSServiceErr_NoError)
        {
            NSLog(@"DNSServiceQueryRecord: %d", error);
            [self.delegate queryDidFail:self withError:error];
        }
    }
        
    - (void)record:(const Record*)theRecord onInterface:(uint32_t)theIndex
    {
        [self.delegate query:self didGetResponse:theRecord onInterface:theIndex];
    }
        
    - (void)recordExpired:(const Record *)theRecord
    {
        [self.delegate query:self recordDidExpire:theRecord];
    }
        
    - (void)failed:(DNSServiceErrorType)theErrorCode
    {
        if (theErrorCode != kDNSServiceErr_Timeout)
        {
            [self.delegate queryDidFail:self withError:theErrorCode];
        }
        else
        {
            [self.delegate queryDidTimeout:self];
        }
    }
        
    @end

4.0 Using The Query Class

The start method of FindServices v4 starts the search by querying for PTR records associated with the service type node.

    ...
    
    - (BOOL)start
    {
        DNSServiceErrorType error = DNSServiceCreateConnection(&dnsServiceRef);
        
        if (error != kDNSServiceErr_NoError)
        {
            NSLog(@"Error: DNSServiceCreateConnection %d", error);
            return NO;
        }
        error = DNSServiceSetDispatchQueue(dnsServiceRef, dispatch_get_main_queue());
        if (error != kDNSServiceErr_NoError)
        {
            NSLog(@"Error: DNSServiceSetDispatchQueue %d", error);
            return NO;
        }
        self.ptrQuery = [[Query alloc] init:self.type type: kDNSServiceType_PTR class:kDNSServiceClass_IN];
        self.ptrQuery.delegate = self;
        [self.ptrQuery start:dnsServiceRef interface:kDNSServiceInterfaceIndexAny timeout:NO];
        return YES;
    }
    
    ...

5.0 Examples

I will forgo the output from the examples as there is only so many console log messages anybody can be expected to find interesting.

Needless to say everything works in pretty much the same way as it did in the three preceding incarnations of the
FindServices class.


Copyright (c) 2013 By Simon Lewis. All Rights Reserved.

Unauthorized use and/or duplication of this material without express and written permission from this blog’s author and owner Simon Lewis is strictly prohibited.

Excerpts and links may be used, provided that full and clear credit is given to Simon Lewis and justanapplication.wordpress.com with appropriate and specific direction to the original content.

November 18, 2013

Service Discovery In Android And iOS: Part Seven – iOS Take Three: Down At C Level

For anyone who considers both Foundation and Core Foundation too rarified there is always a C function API for performing DNS/mDNS based service discovery and registration.

This is declared in the header file

    /usr/include/dns_sd.h

1.0 DNSServiceRefs And Connection Sharing

By default each function in the API which requires DNS functionality establishes a separate connection to the DNS service which it returns as a DNSServiceRef.

In this context the name DNSServiceRef can be a bit confusing.

A DNSServiceRef is a reference to the DNS Service, that is, the thing doing the search for services using DNS, not a reference to a service found using DNS.

There is an alternative to having a per function call connection and DNSServiceRef.

A connection to the DNS service can be established separately and then shared by passing it to each function that would otherwise create a new connection.

2.0 The Function Pattern

All the functions in the API which access the DNS service are declared using a common pattern

    DNSServiceErrorType <function-name>(
                            DNSServiceRef*           sdRef,
                            DNSServiceFlags          flags,
                            uint32_t                 interfaceIndex,
        
                            ... <function specific arguments> ...
    
                            <function specific type> callBack,
                            void*                    context);

2.1 The sdRef Argument

    DNSServiceRef*  sdRef

The sdRef argument is either

  • a pointer to an uninitalized DNSServiceRef which will be initialized to a valid DNSServiceRef if the call succeeds, or

  • a pointer to a shared DNSServiceRef which should be used by the function

2.2 The flags argument

    DNSServiceFlags flags

The flags argument unsurprisingly specifies zero or more flags. If an initialized DNSServiceRef is being passed via the sdRef argument then the flag

    kDNSServiceFlagsShareConnection

must be set.

2.3 The interfaceIndex Argument

    uint32_t   interfaceIndex

The index of the network interface to use to perform the requested DNS operation(s).

If the specific network interface is not important then when starting the search for services the constant

    kDNSServiceInterfaceIndexAny

can be used.

When a service is found the index of the network interface it is associated with is reported and subsequent calls can use this value.

2.4 The callBack Argument

The type of the callBack argument is specific to the function to which it is being passed but in each case it specifies the function to be invoked when a a result is available or an error occurs.

2.5 The info Argument

    void*  context

The value of the context argument will be passed as an argument to the callback function specified by
the callBack argument.

3.0 The Callback Function Pattern

All the callback function types are declared using a common pattern.

    typedef void (*<type-name>)(
                        DNSServiceRef       sdRef,
                        DNSServiceFlags     flags,
                        uint32_t            interfaceIndex,
                        DNSServiceErrorType errorCode,
    
                        ... <function specific arguments> ...

                        void*               context);

3.1 The sdRef Argument

The DNSServiceRef which was passed to the function which invoked this callback.

3.2 The flags Argument

The flags argument is used to pass general status information, e.g., if the

    kDNSServiceFlagsMoreComing

flag is set then this callback will be invoked again.

3.3 The interfaceIndex Argument

The index of the network interface on which the result was obtained.

3.4 The errorCode Argument

If the errorCode argument is not

    kDNSServiceErr_NoError

then an error has occurred.

3.5 The context Argument

The value of the context argument passed to the function which invoked this callback.

4.0 Searching For Services

4.1 DNSServiceBrowse

We can start the search for services of a given type by using the function DNSServiceBrowse
which is declared like this

    DNSServiceErrorType DNSServiceBrowse(
                            DNSServiceRef*        sdRef,
                            DNSServiceFlags       flags,
                            uint32_t              interfaceIndex,
                            const char*           regtype,
                            const char*           domain,
                            DNSServiceBrowseReply callBack,
                            void*                 context);

The regtype argument should be the domain relative type name, e.g.,

    "_ipp.tcp."

The domain argument should be the absolute name of the domain to search in, e.g.,

    "local."

4.2 The DNSServiceBrowse Callback Function

The function passed as the callBack argument to DNSServiceBrowse will be called once for each service of the given type that is found.

If the information about a service that was found becomes invalid, implying that it has ‘disappeared’, then the callback function will called again.’

4.3 The DNSServiceBrowseReply Function Type

The function type DNSServiceBrowseReply is declared like this

    typedef void (*DNSServiceBrowseReply)(
                       DNSServiceRef       sdRef,
                       DNSServiceFlags     flags,
                       uint32_t            interfaceIndex,
                       DNSServiceErrorType errorCode,
                       const char*         serviceName,
                       const char*         regtype,
                       const char*         replyDomain,
                       void*               context);

When a function of this type is invoked, then if the errorCode argument is kDNSServiceErr_NoError

  • serviceName is the type relative name of the service.

  • regtype is the domain relative name of the service type

  • replyDomainis the absolute name of the domain the service is registered in

The kDNSServiceFlagsAdd flag will be set in the flags argument if the service has been found, and clear if the service has been ‘lost’.

5.0 Resolving Services

Resolving a service involves two functions

    DNSServiceResolve

which obtains the service’s SRV and TXT records, and

and

    DNSServiceGetAddrInfo.

which obtains the address or addresses of the host on which the service is running

5.1 DNSServiceResolve

We can obtain the information contained in the SRV and TXT records associated with a given service by using the function
DNSServiceResolve which is declared like this

    DNSServiceErrorType DNSServiceResolve(
                            DNSServiceRef*         sdRef,
                            DNSServiceFlags        flags,
                            uint32_t               interfaceIndex,
                            const char*            name,
                            const char*            regtype,
                            const char*            domain,
                            DNSServiceResolveReply callBack,
                            void*                  context);

The name argument should be the type relative name of the service.

The regtype argument should be the domain relative name of the service type.

The domain argument should be the absolute name of the domain in which the service is registered.

5.1.1 The DNSServiceResolve Callback Function

The function passed as the callBack argument to DNSServiceResolve will be called once, either with the results of with an error.

5.1.1 The DNSServiceResolveReply Function Type

The function type DNSServiceResolveReply is declared like this

    typedef void (*DNSServiceResolveReply)(
                       DNSServiceRef        sdRef,
                       DNSServiceFlags      flags,
                       uint32_t             interfaceIndex,
                       DNSServiceErrorType  errorCode,
                       const char*          fullname,
                       const char*          hosttarget,
                       uint16_t             port,
                       uint16_t             txtLen,
                       const unsigned char* txtRecord,
                       void*                context);

When a function of this type is invoked, then, if the errorCode argument is kDNSServiceErr_NoError

  • fullname is the absolute name of the service, e.g., "ipp_server_1._ipp._tcp.local.".

  • hosttarget is the name of the host the service is running on.

  • port is the port, in network byte order, the service is listening on.

  • txtLen is is the length of the TXT record data.

  • txtRecord is a pointer to the TXT record data itself.

5.2 DNSServiceGetAddrInfo

We can obtain the address of a host using the function DNSServiceGetAddrInfo which is declared like this

    DNSServiceErrorType DNSServiceGetAddrInfo(
                            DNSServiceRef*             sdRef,
                            DNSServiceFlags            flags,
                            uint32_t                   interfaceIndex,
                            DNSServiceProtocol         protocol,
                            const char*                hostname,
                            DNSServiceGetAddrInfoReply callBack,
                            void*                      context);

If the

    kDNSServiceFlagsTimeout

is set in the flags argument then the operation may timeout after a system defined amount of time.

The protocol argument specifies the type of the address requested.

The value should be one of

  • 0

  • kDNSServiceProtocol_IPv4

  • kDNSServiceProtocol_IPv6

  • kDNSServiceProtocol_IPv4|kDNSServiceProtocol_IPv6

A value of 0 (zero) is usually equivalent to requesting both the IPv4 and IPv6 addresses.

The hostname argument should be the absolute name of the host.

5.2.1 The DNSServiceGetAddrInfo Callback Function

The function passed as the callBack argument to DNSServiceGetAddrInfo will be called once for each address type that was requested and is found

It will also be called if the address of the host becomes invalid, e.g., because the host has been turned off.

5.2.2 The DNSServiceGetAddrInfoReply Function Type

The function type DNSServiceGetAddrInfoReply is declared like this

    typedef void (*DNSServiceGetAddrInfoReply)(
                       DNSServiceRef          sdRef,
                       DNSServiceFlags        flags,
                       uint32_t               interfaceIndex,
                       DNSServiceErrorType    errorCode,
                       const char*            hostname,
                       const struct sockaddr* address,
                       uint32_t               ttl,
                       void*                  context);

When a function of this type is invoked, then, if the errorCode argument is kDNSServiceErr_NoError

  • hostname is the name of the host whose address this is

  • address is a pointer to its address, and

  • ttl is the time in seconds for which the given address is valid

The kDNSServiceFlagsAdd flag will be set in the flags argument if the address has been ‘found’, and clear if the address is no longer valid.

The kDNSServiceFlagsMoreComing will be set in the flags argument if there are more addresses, and will be clear if this is the last address.

The type of the address will of course depend upon what what specified as the protocol argument in the call to DNSServiceGetAddrInfo.

If both IPv4 and IPv6 addresses were requested then it will be necessary to examine the sa_family field of the sockaddr struct to find out which one it is.

6.0 The Care And Maintenance Of Your DNSServiceRef

Something that is not perhaps immediately apparent is that the shared DNSServiceRef or one created by a function like DNSServiceBrowse has to be actively handled on the client side.

There are two ways to do this, either

  • by obtaining the file descriptor associated with the connection by calling DNSServiceRefSockFD and doing it all yourself, or

  • by calling the function DNSServiceSetDispatchQueue which will result in the connection being handled ‘automatically’ on the dispatch queue of your choice.

6.1 DNSServiceRefSockFD

The function DNSServiceRefSockFD is declared like this

    int DNSSD_API DNSServiceRefSockFD(DNSServiceRef sdRef);

It takes a DNSServiceRef and returns the file descriptor of the underlying connection to the DNS service.

Once you have obtained your file descriptor you will need to determine when it is readable.

To do this you are going to need either

  • an fd_set and a system call, or

  • a pollfd struct and a different system call

6.1.1 Using select

To use the select system call and assuming sr is the DNSServiceRef you will need to do something like this.

    ...
    
    int fd = DNSServiceRefSockFD(sr);
    
    if (fd == -1)
    {
        fprintf(stderr, "fd == -1 !");
        return;
    }
    
    fd_set         readFDs;
    struct timeval tv;
    
    while (true)
    {
        FD_ZERO(&readFDs);
        FD_SET(fd, &readFDs);
    
        tv.tv_sec  = 1000000;
        tv.tv_usec = 0;
    
        int status = select(fd + 1, &readFDs, NULL, NULL, &tv);
    
        if (status == -1)
        {
            fprintf(stderr, "status == -1\n");
            break;
        }
        else
        if (status == 0)
        {
            fprintf(stderr, "status == 0\n");
        }
        else
        if (FD_ISSET(fd, &readFDs))
        {
            int error = DNSServiceProcessResult(sr);
    
            if (error != kDNSServiceErr_NoError)
            {
                fprintf(stderr, "DNSServiceProcessResult: error == %d\n", error);
                break;
            }
        }
    }

    ...
    

When the file descriptor is readable the function DNSServiceProcessResult is invoked to handle the input. It is this call that results in callback functions being invoked.

This assumes that you are sharing a single DNSServiceRef if not then you are going to end up knee deep in file descriptors and its all going to get very messy very fast.

6.1.2 Using poll

If the use of select is too retro for you you can always use the new-fangled poll system call.

The code looks very similar because poll is just select with unlimited [1] file descriptors.

    ...

    int fd = DNSServiceRefSockFD(sr);
    
    if (fd == -1)
    {
        NSLog(@"fd == -1 !");
        return;
    }
    
    struct pollfd   pollFD;
    
    while (true)
    {
        pollFD.fd = fd;
        pollFD.events = POLL_IN;
        
        int status = poll(&pollFD, 1 , 1000000);
    
        if (status == -1)
        {
            fprintf(stderr, "status == -1\n");
            break;
        }
        else
        if (status == 0)
        {
            fprintf(stderr, "status == 0\n");
        }
        else
        if ((pollFD.revents & POLL_IN) != 0)
        {
            int error = DNSServiceProcessResult(sr);

            if (error != kDNSServiceErr_NoError)
            {
                fprintf(stderr, "DNSServiceProcessResult: error == %d\n", error);
                break;
            }
        }
    }

    ...

6.2 DNSServiceSetDispatchQueue

The alternative to wrestling with file descriptors is the function DNSServiceSetDispatchQueue
which is declared like this

    DNSServiceErrorType DNSServiceSetDispatchQueue(
                            DNSServiceRef    service,
                            dispatch_queue_t queue);

The DNSServiceRef can be associated with a shared connection or with a per function connection.

See below for an example of its use.

7.0 Creating A DNSServiceRef For A Shared Connection

The only way to create a DNSServiceRef for a connection which can be shared is by using the function
DNSServiceCreateConnection which is declared like this

   DNSServiceErrorType DNSServiceCreateConnection(DNSServiceRef* sdRef);

A copy of the initialized DNSServiceRef that results should be passed to each function that is going to share the connection.

See below for an example of its use.

8.0 DNSServiceBrowse In Action

This is the start method of the third version of the FindServices class.

    - (BOOL)start
    {
        DNSServiceErrorType error = DNSServiceCreateConnection(&dnsServiceRef);
    
        if (error != kDNSServiceErr_NoError)
        {
            NSLog(@"Error: DNSServiceCreateConnection %d", error);
            return NO;
        }
        error = DNSServiceSetDispatchQueue(dnsServiceRef, dispatch_get_main_queue());
        if (error != kDNSServiceErr_NoError)
        {
            NSLog(@"Error: DNSServiceSetDispatchQueue %d", error);
            return NO;
        }
        browseRef = dnsServiceRef;
        error = DNSServiceBrowse(
                    &browseRef,
                    kDNSServiceFlagsShareConnection,
                    kDNSServiceInterfaceIndexAny,
                    [self.type UTF8String],
                    [self.domain UTF8String],
                    browseCallback,
                    (__bridge void*)self);
        if (error != kDNSServiceErr_NoError)
        {
            NSLog(@"Error: DNSServiceBrowse %d", error);
            return NO;
        }
        return YES;
    }
    static void browseCallback(
                    DNSServiceRef       sdRef,
                    DNSServiceFlags     theFlags,
                    uint32_t            theInterfaceIndex,
                    DNSServiceErrorType theErrorCode,
                    const char*         theName,
                    const char*         theType,
                    const char*         theDomain,
                    void*               theContext)
    {
        NSLog(@"browseCallback:  error == %d flags == %s", theErrorCode, flagsToString(theFlags));
        
        if (theErrorCode == kDNSServiceErr_NoError)
        {
            ServiceIdentifier si = { theName, theType, theDomain };
        
            if ((theFlags & kDNSServiceFlagsAdd) != 0)
            {
                [(__bridge FindServices*)theContext serviceFound:&si onInterface:theInterfaceIndex];
            }
            else
            {
                [(__bridge FindServices*)theContext serviceLost:&si];
            }
        }
        else
        {
            [(__bridge FindServices*)theContext browseFailed:theErrorCode];
        }
    }

9.0 DNSServiceResolve In Action

This is the resolve:onInterface: method of the ServiceResolver class

    - (void)resolve:(ServiceIdentifier*)theServiceId onInterface:(uint32_t)theInterfaceIndex
    {
        DNSServiceErrorType error;
        
        error = DNSServiceResolve(
                    &resolveRef,
                    kDNSServiceFlagsShareConnection,
                    theInterfaceIndex,
                    theServiceId->name,
                    theServiceId->type,
                    theServiceId->domain,
                    resolveCallback,
                    (__bridge void*)self);
        if (error != kDNSServiceErr_NoError)
        {
            NSLog(@"DNSServiceResolve: %d", error);
            [self.delegate serviceResolver:self didFail:error];
        }
    }

and this is the associated callback function.

    static void resolveCallback(
                    DNSServiceRef        theRef,
                    DNSServiceFlags      theFlags,
                    uint32_t             theInterfaceIndex,
                    DNSServiceErrorType  theErrorCode,
                    const char*          theFullName,
                    const char*          theTarget,
                    uint16_t             thePort,
                    uint16_t             theTXTRecordLength,
                    const unsigned char* theTXTRecord,
                    void*                theContext)
    {
        NSLog(@"resolveCallback: error == %d flags == %s", theErrorCode, flagsToString(theFlags));
        
        if (theErrorCode != kDNSServiceErr_NoError)
        {
            NSLog(@"resolveCallback: error !");
            [(__bridge ServiceResolver*)theContext resolveFailed:theErrorCode];
        }
        else
        if (theFlags == 0)
        {
            ServiceInfo si =
                {
                    theFullName,
                    theTarget,
                    ntohs(thePort),
                    theTXTRecordLength,
                    theTXTRecord
                };
        
            NSLog(@"%s %s %u", theFullName, theTarget, thePort);
        
            [(__bridge ServiceResolver*)theContext resolved:&si onInterface:theInterfaceIndex];
        }
        else
        {
            NSLog(@"resolveCallback: flags set !");
            [(__bridge ServiceResolver*)theContext internalError];
        }
    }

10.0 DNSServiceGetAddrInfo In Action

This is the resolved:onInterface: method of the ServiceResolver class

    - (void)resolved:(const ServiceInfo*)theServiceInfo onInterface:(uint32_t)theInterfaceIndex
    {
        DNSServiceErrorType error;
        
        error = DNSServiceGetAddrInfo(
                    &addressRef,
                    kDNSServiceFlagsShareConnection,
                    theInterfaceIndex,
                    kDNSServiceProtocol_IPv4|kDNSServiceProtocol_IPv6,
                    theServiceInfo->target,
                    addressInfoCallback,
                    (__bridge void*)self);
        if (error == kDNSServiceErr_NoError)
        {
            [self.builder serviceInfo:theServiceInfo];
        }
        else
        {
            NSLog(@"DNSServiceGetAddrInfo: %d", error);
            [self.delegate serviceResolver:self didFail:error];
        }
    }

and this is the associated callback function.

    static void addressInfoCallback(
                    DNSServiceRef          theServiceRef,
                    DNSServiceFlags        theFlags,
                    uint32_t               theInterfaceIndex,
                    DNSServiceErrorType    theErrorCode,
                    const char*            theHostname,
                    const struct sockaddr* theAddress,
                    uint32_t               theTTL,
                    void*                  theContext)
    {
        NSLog(@"addressInfoCallback: error == %d flags == %s ", theErrorCode, flagsToString(theFlags));
        
        if (theErrorCode != kDNSServiceErr_NoError)
        {
            NSLog(@"addressInfoCallback error");
            [(__bridge ServiceResolver*)theContext getAddrInfoFailed:theErrorCode];
        }
        else
        if ((theFlags & kDNSServiceFlagsAdd) != 0)
        {
            NSLog(@"theHostname == %s", theHostname);
            NSLog(@"theAddress->sa_family == %d", theAddress->sa_family);
        
            [(__bridge ServiceResolver*)theContext address:theAddress];
            if ((theFlags & kDNSServiceFlagsMoreComing) == 0)
            {
                [(__bridge ServiceResolver*)theContext done];
            }
        }
        else
        {
            NSLog(@"theHostname == %s", theHostname);
            NSLog(@"theAddress->sa_family == %d", theAddress->sa_family);
            // ignore
        }
    }

11.0 Examples

In each case FindServices is looking for services of type

    "_ipp._tcp."

in the domain

    "local."

In each case the log output is from FindServices and its delegate running on an iPad running iOS 7.0.

7.1 A Single IPPServer

A single instance of the CUPS test server IPPServer with the name ipp_server_1
running on a Mac and then being stopped.

In this case the addressInfoCallback function is called twice, first with the IPv6 address then with the IPv4 address.

    ...
        
    2013-11-18 14:53:20.304 XperTakeThree[334:60b] browseCallback:  error == 0 flags == kDNSServiceFlagsAdd
    2013-11-18 14:53:20.307 XperTakeThree[334:60b] serviceFound: ipp_server_1._ipp._tcp.local.
    2013-11-18 14:53:20.309 XperTakeThree[334:60b] resolveCallback: error == 0 flags == <none>
    2013-11-18 14:53:20.310 XperTakeThree[334:60b] ipp_server_1._ipp._tcp.local. Simons-Computer.local. 56088
    2013-11-18 14:53:20.312 XperTakeThree[334:60b] addressInfoCallback: error == 0 flags == kDNSServiceFlags{Add,MoreComing}
    2013-11-18 14:53:20.313 XperTakeThree[334:60b] theHostname == Simons-Computer.local.
    2013-11-18 14:53:20.314 XperTakeThree[334:60b] theAddress->sa_family == 30
    2013-11-18 14:53:20.315 XperTakeThree[334:60b] addressInfoCallback: error == 0 flags == kDNSServiceFlagsAdd
    2013-11-18 14:53:20.316 XperTakeThree[334:60b] theHostname == Simons-Computer.local.
    2013-11-18 14:53:20.317 XperTakeThree[334:60b] theAddress->sa_family == 2
    2013-11-18 14:54:18.545 XperTakeThree[334:60b] browseCallback:  error == 0 flags == <none>
    2013-11-18 14:54:18.547 XperTakeThree[334:60b] serviceLost: name == ipp_server_1._ipp._tcp.local.
        
    ...

11.2 A Single Printer

A printer being turned on and then turned off a couple of minutes later.

In this case we only get a single address, the IPV4 one, but we do get a second call to the function addressInfoCallback
function when the printer is turned off

    ...
        
    2013-11-18 14:55:55.137 XperFS_DNS_SD[351:60b] browseCallback:  error == 0 flags == kDNSServiceFlagsAdd
    2013-11-18 14:55:55.140 XperFS_DNS_SD[351:60b] serviceFound: Canon MG6200 series._ipp._tcp.local.
    2013-11-18 14:55:55.141 XperFS_DNS_SD[351:60b] resolveCallback: error == 0 flags == <none>
    2013-11-18 14:55:55.142 XperFS_DNS_SD[351:60b] Canon32MG620032series._ipp._tcp.local. 7D300C000000.local. 30466
    2013-11-18 14:55:55.144 XperFS_DNS_SD[351:60b] addressInfoCallback: error == 0 flags == kDNSServiceFlagsAdd
    2013-11-18 14:55:55.145 XperFS_DNS_SD[351:60b] theHostname == 7D300C000000.local.
    2013-11-18 14:55:55.146 XperFS_DNS_SD[351:60b] theAddress->sa_family == 2
    2013-11-18 15:02:18.835 XperFS_DNS_SD[351:60b] addressInfoCallback: error == 0 flags == <none>
    2013-11-18 15:02:18.837 XperFS_DNS_SD[351:60b] theHostname == 7D300C000000.local.
    2013-11-18 15:02:18.839 XperFS_DNS_SD[351:60b] theAddress->sa_family == 2
    2013-11-18 15:02:19.936 XperFS_DNS_SD[351:60b] browseCallback:  error == 0 flags == <none>
    2013-11-18 15:02:19.938 XperFS_DNS_SD[351:60b] serviceLost: name == Canon MG6200 series._ipp._tcp.local.

    ...

Notes

  • Subject to terms and conditions. The number of file descriptors may be subject to limits.

Copyright (c) 2013 By Simon Lewis. All Rights Reserved.

Unauthorized use and/or duplication of this material without express and written permission from this blog’s author and owner Simon Lewis is strictly prohibited.

Excerpts and links may be used, provided that full and clear credit is given to Simon Lewis and justanapplication.wordpress.com with appropriate and specific direction to the original content.

November 12, 2013

Service Discovery In Android And iOS: Part Five – iOS Take One

When it comes to iOS we are spoilt for choice. There are no less than three APIs available for service discovery.

Starting at the Foundation level we have the Objective-C class NSNetServiceBrowser.

1.0 Instance Creation

The NSNetServiceBrowser class defines a single no argument init method so to create one we simply do this

    browser = [[NSNetServiceBrowser alloc] init];

2.0 Starting A Search

The search for services of a given type is asynchronous.

To start the search we call the method

    - (void)searchForServicesOfType:(NSString*)type inDomain:(NSString*)domainString;

The type argument should be the domain relative name of the service type to search for, e.g.,

    "_ipp._tcp."

Note the dot (‘.’) at the end.

The domainString should be the absolute name of the domain to search, e.g.,

    "local."

Note the dot (‘.’) at the end.

Once the search has started it will continue indefinitely unless it is explicitly stopped.

3.0 NSNetServiceBrowserDelegate

NSNetServiceBrowser uses the standard delegate pattern to return its results.

The delegate is required to implement the NSNetServiceBrowserDelegate protocol.

3.1 netServiceBrowserWillSearch:

Following the call to the method searchForServicesOfType:inDomain: if the NSNetServiceBrowser instance is going to perform the search it calls the delegate’s implementation of the method

    - (void)netServiceBrowserWillSearch:(NSNetServiceBrowser*)netServiceBrowser

3.2 netServiceBrowser:didNotSearch:

Following the call to the method searchForServicesOfType:inDomain: if the NSNetServiceBrowser instance is not going to perform the search it calls the delegate’s implementation of the method

    - (void)netServiceBrowser:(NSNetServiceBrowser*)netServiceBrowser didNotSearch:(NSDictionary*)errorInfo

The easiest way to see this method in action is to get the type name wrong in the call to searchForServicesOfType:inDomain:, e.g.,

    "._ipp.tcp."

in which case the NSDictionary passed as the errorInfo argument will look like this

    {
        NSNetServicesErrorCode   = "-72004";
        NSNetServicesErrorDomain = 10;
    }

You can find the error codes in NSNetServices.h.

3.3 netServiceBrowser:didFindService:moreComing:

Following the call to the method searchForServicesOfType:inDomain: if the NSNetServiceBrowser instance finds a service of the given type it calls the delegate’s implementation of the method

    - (void)netServiceBrowser:
                (NSNetServiceBrowser*)netServiceBrowser
            didFindService:
                (NSNetService*)netService
            moreComing:
                (BOOL)moreServicesComing

3.4 netServiceBrowser:didRemoveService:moreComing:

If a service that has previously been found is no longer available the NSNetServiceBrowser instance calls the delegate’s implementation of the method

    - (void)netServiceBrowser:
                (NSNetServiceBrowser*)netServiceBrowser
            didRemoveService:
                (NSNetService*)netService
            moreComing:
                (BOOL)moreServicesComing

4.0 NSNetService

As discovered, the service as represented by the NSNetService instance is still in a nascent state. Neither its address nor the key/value pairs in its TXT record are available.

To be useful it has to be resolved.

The resolution of a service is performed asynchronously. It is started by invoking the NSNetService method resolveWithTimeout: which is declared like this

    - (void)resolveWithTimeout:(NSTimeInterval)timeout

Once started the resolution of a service will either complete successfully ot time out after the interval specified by the timeout argument.

5.0 NSNetServiceDelegate

The success or failure of the resolution of a NSNetService instance is reported to the delegate of that instance.

The delegate must implement the NSNetServiceDelegate protocol.

5.1 netServiceWillResolve:

Following the call to the resolveWithTimeout: method the NSNetService instance will call its delegate’s implementation of the method

    - (void)netServiceWillResolve:(NSNetService*)sender

5.2 netService:didNotResolve:

If the resolution of the service fails the NSNetService instance calls its delegate’s implementation of the method

    - (void)netService:(NSNetService *)sender didNotResolve:(NSDictionary *)errorDict

5.3 netServiceDidResolveAddress:

If the resolution of the service succeeds the NSNetService instance calls its delegate’s implementation of the method

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

There is a caveat however. As we shall see ‘success’ in this context does not always mean what you might expect.

6.0 The FindServices Class

To make things slightly simpler we can wrap up the classes and their delegates in a single class FindServices
as we did in the Java case.

FindServicesDelegate.h

    //
    //  FindServicesDelegate.h
    //  XperTakeOne
    //
    //  Created by Simon Lewis on 03/11/2013.
    //  Copyright (c) 2013 Simon Lewis. All rights reserved.
    //
        
    #import <Foundation/Foundation.h>
        
    @class FindServices;
    @class Service;
        
    @protocol FindServicesDelegate <NSObject>
        
    - (void)findServices:(FindServices*)theFindServices didFindService:(Service*)theService;
        
    - (void)findServices:(FindServices*)theFindServices didLoseService:(Service*)theService;
        
    @end

FindServices.h

    //
    //  FindServices.h
    //  XperTakeOne
    //
    //  Created by Simon Lewis on 03/11/2013.
    //  Copyright (c) 2013 Simon Lewis. All rights reserved.
    //
        
    #import <Foundation/Foundation.h>
        
    #import "FindServicesDelegate.h"
        
    @interface FindServices : NSObject<NSNetServiceBrowserDelegate, NSNetServiceDelegate>
        
    @property (weak) id<FindServicesDelegate>   delegate;
        
    - (FindServices*)initWithType:(NSString*)theType andDomain:(NSString*)theDomain;
        
    - (void)start;
        
    @end

FindServices.m

    //
    //  FindServices.m
    //  XperTakeOne
    //
    //  Created by Simon Lewis on 03/11/2013.
    //  Copyright (c) 2013 Simon Lewis. All rights reserved.
    //
        
    #import "Service.h"
        
    #import "FindServices.h"
        
    @interface FindServices ()
        
    @property NSString*             type;
    @property NSString*             domain;
    @property NSNetServiceBrowser*  browser;
    @property NSMutableArray*       resolving;
    @property NSMutableDictionary*  services;
        
    @end
        
    @implementation FindServices
        
    - (FindServices*)initWithType:(NSString*)theType andDomain:(NSString*)theDomain
    {
        self = [super init];
        if (self != nil)
        {
            self.type      = theType;
            self.domain    = theDomain;
            self.browser   = [[NSNetServiceBrowser alloc] init];
            self.resolving = [NSMutableArray arrayWithCapacity:8];
            self.services  = [NSMutableDictionary dictionaryWithCapacity:8];
        
            self.browser.delegate = self;
        }
        return self;
    }
        
    - (void)start
    {
        [self.browser searchForServicesOfType:self.type inDomain:self.domain];
    }
        
    // NSNetServiceBrowserDelegate
        
    - (void)netServiceBrowserWillSearch:(NSNetServiceBrowser *)theBrowser
    {
        NSLog(@"netServiceBrowserWillSearch:\n");
    }
        
    - (void)netServiceBrowser:(NSNetServiceBrowser *)theBrowser didNotSearch:(NSDictionary *)theErrors
    {
        NSLog(@"netServiceBrowser:didNotSearch: %@", theErrors);
    }
        
    - (void)netServiceBrowser:
                (NSNetServiceBrowser *)aNetServiceBrowser
            didFindService:
                (NSNetService *)theService
            moreComing:
                (BOOL)moreComing
    {
        NSLog(@"netServiceBrowser:didFindService: %@", theService);
        
        [self.resolving addObject:theService];
        theService.delegate = self;
        [theService resolveWithTimeout:0.0];
    }
        
    - (void)netServiceBrowser:
                (NSNetServiceBrowser *)aNetServiceBrowser
            didRemoveService:
                (NSNetService *)theService
            moreComing:
                (BOOL)moreComing
    {
        NSLog(@"netServiceBrowser:didRemoveService: %@", theService);
        
        Service* service = [self.services objectForKey:theService.name];
        
        if (service != nil)
        {
            [self.services removeObjectForKey:theService.name];
            [self.delegate findServices:self didLoseService:service];
        }
        else
        {
            NSLog(@"%@ removed without being found ?", theService.name);
        }
    }
        
    // NSNetServiceDelegate
        
    - (void)netServiceWillResolve:(NSNetService *)theService
    {
        NSLog(@"netServiceWillResolve");
    }
        
    - (void)netServiceDidResolveAddress:(NSNetService *)theService
    {
        NSUInteger nAddresses = [[theService addresses] count];
        
        NSLog(@"netServiceDidResolveAddress: %@ nAddresses == %lu", theService, (unsigned long)nAddresses);
        
        if (nAddresses != 0)
        {
            Service* service = [[Service alloc] init:theService];
        
            [self.resolving removeObject:theService];
            [self.services setObject:service forKey:theService.name];
            [self.delegate findServices:self didFindService:service];
        }
        else
        {
            Service* service = [self.services objectForKey:theService.name];
        
            if (service != nil)
            {
                NSLog(@"service %@ now has 0 addresses !", theService.name);
            }
            else
            {
                NSLog(@"resolve failed ? %@ has 0 addresses", theService.name);
            }
        }
    }
        
    - (void)netService:(NSNetService *)theService didNotResolve:(NSDictionary *)theErrors
    {
        NSLog(@"netServiced:didNotResolve: %@ %@", theService, theErrors);
        
        [self.resolving removeObject:theService];
    }
        
    @end

7.0 Examples

In each case FindServices is looking for services of type

    "_ipp._tcp."

in the domain

    "local."

In each case the log output is from FindServices and its delegate running on an iPad running iOS 7.0.

7.1 A Single IPPServer

A single instance of the CUPS test server IPPServer with the name ipp_server_1 running on a Mac and then being stopped.

    ...

    2013-11-12 08:26:05.516 XperTakeOne[163:60b] netServiceBrowserWillSearch:
    2013-11-12 08:26:12.500 XperTakeOne[163:60b] netServiceBrowser:didFindService: \
        <NSNetService 0x1464bd60> local. _ipp._tcp. ipp_server_1
    2013-11-12 08:26:12.504 XperTakeOne[163:60b] netServiceWillResolve
    2013-11-12 08:26:12.533 XperTakeOne[163:60b] netServiceDidResolveAddress: \
        <NSNetService 0x1464bd60> local. _ipp._tcp. ipp_server_1 nAddresses == 2
    2013-11-12 08:26:12.535 XperTakeOne[163:60b] findServices:didFindService: <Service: 0x14631890>
    2013-11-12 08:27:56.204 XperTakeOne[163:60b] netServiceBrowser:didRemoveService: \
        <NSNetService 0x14522f50> local. _ipp._tcp. ipp_server_1
    2013-11-12 08:27:56.207 XperTakeOne[163:60b] findServices:didLoseService: <Service: 0x14631890>

    ...

7.2 Two IPPServers

Two instances of the CUPS test server IPPServer with the names ipp_server_1 and ipp_server_2 running on a Mac and then being stopped.

    ...

    2013-11-12 08:29:54.404 XperTakeOne[171:60b] netServiceBrowserWillSearch:
    2013-11-12 08:29:54.525 XperTakeOne[171:60b] netServiceBrowser:didFindService: \
        <NSNetService 0x1757ac10> local. _ipp._tcp. ipp_server_1
    2013-11-12 08:29:54.528 XperTakeOne[171:60b] netServiceWillResolve
    2013-11-12 08:29:54.531 XperTakeOne[171:60b] netServiceBrowser:didFindService: \
        <NSNetService 0x17578140> local. _ipp._tcp. ipp_server_2
    2013-11-12 08:29:54.533 XperTakeOne[171:60b] netServiceWillResolve
    2013-11-12 08:29:55.553 XperTakeOne[171:60b] netServiceDidResolveAddress:\
        <NSNetService 0x17578140> local. _ipp._tcp. ipp_server_2 nAddresses == 2
    2013-11-12 08:29:55.556 XperTakeOne[171:60b] findServices:didFindService: \
        <Service: 0x17673570>
    2013-11-12 08:29:55.558 XperTakeOne[171:60b] netServiceDidResolveAddress: \
        <NSNetService 0x1757ac10> local. _ipp._tcp. ipp_server_1 nAddresses == 2
    2013-11-12 08:29:55.559 XperTakeOne[171:60b] findServices:didFindService: <Service: 0x176b25f0>
    2013-11-12 08:30:57.454 XperTakeOne[171:60b] netServiceBrowser:didRemoveService: \
        <NSNetService 0x1757e7d0> local. _ipp._tcp. ipp_server_2
    2013-11-12 08:30:57.457 XperTakeOne[171:60b] findServices:didLoseService: <Service: 0x17673570>
    2013-11-12 08:31:02.678 XperTakeOne[171:60b] netServiceBrowser:didRemoveService: \
        <NSNetService 0x17581730> local. _ipp._tcp. ipp_server_1
    2013-11-12 08:31:02.680 XperTakeOne[171:60b] findServices:didLoseService: <Service: 0x176b25f0>
    
    ...

7.3 A Single Printer

A printer being turned on and then turned off five minutes later.

Note the lines shown in bold for emphasis.

When the printer is turned off the netServiceDidResolveAddress: method is being called for a second time but this time the NSNetService instance has no addresses.

This is the reason for the convoluted code in the FindServices implementation of the netServiceDidResolveAddress:.

Note also that this does not happen when an IPPServer instance is shutdown.

    ...

    2013-11-12 08:32:14.253 XperTakeOne[179:60b] netServiceBrowserWillSearch:
    2013-11-12 08:32:14.976 XperTakeOne[179:60b] netServiceBrowser:didFindService: \
        <NSNetService 0x146b3a50> local. _ipp._tcp. Canon MG6200 series
    2013-11-12 08:32:14.979 XperTakeOne[179:60b] netServiceWillResolve
    2013-11-12 08:32:15.008 XperTakeOne[179:60b] netServiceDidResolveAddress: \
        <NSNetService 0x146b3a50> local. _ipp._tcp. Canon MG6200 series nAddresses == 1
    2013-11-12 08:32:15.011 XperTakeOne[179:60b] findServices:didFindService: <Service: 0x14681460>

    2013-11-12 08:37:10.250 XperTakeOne[179:60b] netServiceDidResolveAddress: \
        <NSNetService 0x146b3a50> local. _ipp._tcp. Canon MG6200 series nAddresses == 0
    2013-11-12 08:37:10.252 XperTakeOne[179:60b] service Canon MG6200 series now has 0 addresses !

    2013-11-12 08:37:11.325 XperTakeOne[179:60b] netServiceBrowser:didRemoveService: \
        <NSNetService 0x146b21d0> local. _ipp._tcp. Canon MG6200 series
    2013-11-12 08:37:11.327 XperTakeOne[179:60b] findServices:didLoseService: <Service: 0x14681460>

    ...

Copyright (c) 2013 By Simon Lewis. All Rights Reserved.

Unauthorized use and/or duplication of this material without express and written permission from this blog’s author and owner Simon Lewis is strictly prohibited.

Excerpts and links may be used, provided that full and clear credit is given to Simon Lewis and justanapplication.wordpress.com with appropriate and specific direction to the original content.

October 29, 2013

Service Discovery in Android And iOS – Part One: The android.net.nsd.NsdManager Class Considered Not Very Useful At All

Suppose I was writing an Android program and for some strange reason I wanted to automatically find any printers on the local network that support the Internet Printing Protocol (IPP).

Quite why I would want to do this is anyone’s guess. Perhaps I want to do something bizarre like support printing from
my program.

Anyway, in theory I am in luck because I can use an instance of the android.net.NsdManager class which supports
mDNS based service discovery.

1.0 Getting An NsdManager Instance

An instance of android.net.nsd.NsdManager can be obtained by a call to the Context.getSystemService
method with the argumentcContext.NSD_SERVICE.

So in an Application’s main Activity we can do something like this

    NsdManager manager = (NsdManager)getSystemService(NSD_SERVICE);

2.0 Starting Service Discovery

The process of service discovery is started by invoking the NsdManager.discoverServices method which is defined like this

    public void discoverServices(String serviceType, int protocolType, NsdManager.DiscoveryListener listener)

The methods defined by the DiscoveryListener instance passed as the listener argument are invoked asynchronously.

3.0 android.net.nsd.NsdManager.DiscoveryListener

The DiscoveryListener interface defines two methods to report the outcome of starting the process of service discovery

    public void onDiscoveryStarted(String serviceType)

    public void onStartDiscoveryFailed(String serviceType, int errorCode)

two methods to report the outcome of stopping the process of service discovery

    public void onDiscoveryStopped(String serviceType)

    public void onStopDiscoveryFailed(String serviceType, int errorCode)

a method to report that a service has been discovered

    public void onServiceFound(NsdServiceInfo serviceInfo)

and a method to report that a previously discovered service has disappeared.

    public void onServiceLost (NsdServiceInfo serviceInfo)

4.0 Resolving A Service

If the onServiceFound method of the DiscoveryListener instance passed to the call to discoverServices is invoked then a service has been discovered.

We can then call the NsdManager.resolveService which is declared like this

    public void resolveService(NsdServiceInfo serviceInfo, NsdManager.ResolveListener listener)

The serviceInfo argument is NsdServiceInfo instance passed to onServiceFound.

The methods defined by the ResolveListener instance passed as the listener argument are invoked asynchronously.

5.0 android.net.nsd.NsdManager.ResolveListener

The ResolveListener interface declares a method to report that a service has been resolved

    public void onServiceResolved(NsdServiceInfo serviceInfo)

and a method to report that it was not possible to resolve a service

    public void onResolveFailed(NsdServiceInfo serviceInfo, int errorCode)

6.0 The FindServicesNSD Class

Here is the source code for the FindServicesNSD class which encapsulates the use of the NsdManager service
discovery methods

    // FindServicesNSD.java
    
    // Copyright (c) 2013 By Simon Lewis. All Rights Reserved.
    
    package xper.villiars;
    
    import android.net.nsd.NsdManager;
    import android.net.nsd.NsdManager.DiscoveryListener;
    import android.net.nsd.NsdManager.ResolveListener;
    import android.net.nsd.NsdServiceInfo;
    import android.util.Log;
    
    final class FindServicesNSD
                implements
                    DiscoveryListener,
                    ResolveListener
    {
        // DiscoveryListener
	
        @Override
        public void onDiscoveryStarted(String theServiceType)
        {
            Log.d(TAG, "onDiscoveryStarted");
        }
    
        @Override
        public void onStartDiscoveryFailed(String theServiceType, int theErrorCode)
        {
            Log.d(TAG, "onStartDiscoveryFailed(" + theServiceType + ", " + theErrorCode);
        }
	
        @Override
        public void onDiscoveryStopped(String serviceType)
        {
            Log.d(TAG, "onDiscoveryStopped");
        }
	
        @Override
        public void onStopDiscoveryFailed(String theServiceType, int theErrorCode)
        {
            Log.d(TAG, "onStartDiscoveryFailed(" + theServiceType + ", " + theErrorCode);
        }
	
        @Override
        public void onServiceFound(NsdServiceInfo theServiceInfo)
        {
            Log.d(TAG, "onServiceFound(" + theServiceInfo + ")");
            Log.d(TAG, "name == " + theServiceInfo.getServiceName());
            Log.d(TAG, "type == " + theServiceInfo.getServiceType());
            serviceFound(theServiceInfo);
        }
    
        @Override
        public void onServiceLost(NsdServiceInfo theServiceInfo)
        {
            Log.d(TAG, "onServiceLost(" + theServiceInfo + ")");
        }
    
        // Resolve Listener
    
        @Override
        public void onServiceResolved(NsdServiceInfo theServiceInfo)
        {
            Log.d(TAG, "onServiceResolved(" + theServiceInfo + ")");
            Log.d(TAG, "name == " + theServiceInfo.getServiceName());
            Log.d(TAG, "type == " + theServiceInfo.getServiceType());
            Log.d(TAG, "host == " + theServiceInfo.getHost());
            Log.d(TAG, "port == " + theServiceInfo.getPort());
	    }
	
        @Override
        public void onResolveFailed(NsdServiceInfo theServiceInfo, int theErrorCode)
        {
            Log.d(TAG, "onResolveFailed(" + theServiceInfo + ", " + theErrorCode);
        }
    
        //
	
        FindServicesNSD(NsdManager theManager, String theServiceType)
        {
            manager     = theManager;
            serviceType = theServiceType;
        }
	
        void run()
        {
            manager.discoverServices(serviceType, NsdManager.PROTOCOL_DNS_SD, this);
        }
	
        private void serviceFound(NsdServiceInfo theServiceInfo)
        {
            manager.resolveService(theServiceInfo, this);
        }
	
        //
	
        private NsdManager   manager;
        private String       serviceType;
	
        //
	
        private static final String TAG = "FindServicesNSD";
    }

7.0 Example

Running an instance of FindServicesNSD created like this

    new FindServicesNSD((NsdManager)getSystemService(NSD_SERVICE), "_ipp._tcp")

on a device on a network with an IPP capable printer present results in the following


    D/FindServicesNSD( 2459): onDiscoveryStarted
    D/FindServicesNSD( 2459): onServiceFound(name:\
        Canon MG6200 seriestype: _ipp._tcp.host: nullport: 0txtRecord: null)
    D/FindServicesNSD( 2459): name == Canon MG6200 series
    D/FindServicesNSD( 2459): type == _ipp._tcp.
    D/FindServicesNSD( 2459): onServiceResolved(name:\
        Canon32MG620032seriestype: ._ipp._tcphost: /10.0.1.5port: 631txtRecord: null)
    D/FindServicesNSD( 2459): name == Canon32MG620032series
    D/FindServicesNSD( 2459): type == ._ipp._tcp
    D/FindServicesNSD( 2459): host == /10.0.1.5
    D/FindServicesNSD( 2459): port == 631

This is output from adb logcat run through grep FindSevicesNSD then slightly edited for clarity.

8.0 android.net.nsd.NsdServiceInfo: Where’s The Rest Of It ?

Given the instance of NsdServiceInfo passed to the onServiceResolved method it is possible to determine, the name and type of the service, the host on which it is running and the port it is listening on.

There is however additional per service information available via the mDNS service discovery mechanism which is not made accessible.[1]

While it may be possible to use a service without the missing information, this is not guaranteed to be the case

Using a service supporting IPP is one example where at least one piece of the missing per-service information is necessary.

9.0 Conclusion

Although the NsdManager class is documented as supporting mDNS based service discovery the deficiency in the implementation means that it ends up being not very useful at all.

Notes

  1. They could have made it accessible, its just that they had it and then they threw it away !


Copyright (c) 2013 By Simon Lewis. All Rights Reserved.

Unauthorized use and/or duplication of this material without express and written permission from this blog’s author and owner Simon Lewis is strictly prohibited.

Excerpts and links may be used, provided that full and clear credit is given to Simon Lewis and justanapplication.wordpress.com with appropriate and specific direction to the original content.

Create a free website or blog at WordPress.com.