test3.c 1.58 KB
O'Reilly Media, Inc. committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
#include <dns_sd.h>
#include <stdio.h>	 // For stdout, stderr
#include <string.h>	 // For strlen(), strcpy(), bzero()

extern void HandleEvents(DNSServiceRef);

static void
MyBrowseCallBack(DNSServiceRef service,
				DNSServiceFlags flags,
				uint32_t interfaceIndex,
				DNSServiceErrorType errorCode,
				const char * name,
				const char * type,
				const char * domain,
				void * context)
	{
	#pragma unused(context)
	if (errorCode != kDNSServiceErr_NoError)
		fprintf(stderr, "MyBrowseCallBack returned %d\n", errorCode);
	else
		{
		char *addString  = (flags & kDNSServiceFlagsAdd) ? "ADD" : "REMOVE";
		char *moreString = (flags & kDNSServiceFlagsMoreComing) ? "MORE" : "    ";
		printf("%-7s%-5s %d%s.%s%s\n",
			addString, moreString, interfaceIndex, name, type, domain);
		}
	if (!(flags & kDNSServiceFlagsMoreComing)) fflush(stdout);
	}

static DNSServiceErrorType
MyDNSServiceBrowse()
	{
	DNSServiceErrorType error;
	DNSServiceRef  serviceRef;
	
	error = DNSServiceBrowse(&serviceRef,
							0,                // no flags
							0,                // all network interfaces
							"_http._tcp",     // service type
							"",               // default domains
							MyBrowseCallBack, // call back function
							NULL);            // no context
	if (error == kDNSServiceErr_NoError)
		{
		HandleEvents(serviceRef); // Add service to runloop to get callbacks
		DNSServiceRefDeallocate(serviceRef);
		}

	return error;
	}

int main (int argc, const char * argv[])
	{
	DNSServiceErrorType error = MyDNSServiceBrowse();
	if (error) fprintf(stderr, "DNSServiceDiscovery returned %d\n", error);
	return 0;
	}