2 * Copyright (c) 2002-2003 Apple Computer, Inc. All rights reserved.
4 * Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Computer, Inc.
5 * ("Apple") in consideration of your agreement to the following terms, and your
6 * use, installation, modification or redistribution of this Apple software
7 * constitutes acceptance of these terms. If you do not agree with these terms,
8 * please do not use, install, modify or redistribute this Apple software.
10 * In consideration of your agreement to abide by the following terms, and subject
11 * to these terms, Apple grants you a personal, non-exclusive license, under Apple's
12 * copyrights in this original Apple software (the "Apple Software"), to use,
13 * reproduce, modify and redistribute the Apple Software, with or without
14 * modifications, in source and/or binary forms; provided that if you redistribute
15 * the Apple Software in its entirety and without modifications, you must retain
16 * this notice and the following text and disclaimers in all such redistributions of
17 * the Apple Software. Neither the name, trademarks, service marks or logos of
18 * Apple Computer, Inc. may be used to endorse or promote products derived from the
19 * Apple Software without specific prior written permission from Apple. Except as
20 * expressly stated in this notice, no other rights or licenses, express or implied,
21 * are granted by Apple herein, including but not limited to any patent rights that
22 * may be infringed by your derivative works or by other works in which the Apple
23 * Software may be incorporated.
25 * The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO
26 * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED
27 * WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
28 * PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN
29 * COMBINATION WITH YOUR PRODUCTS.
31 * IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR
32 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
33 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
34 * ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION
35 * OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT
36 * (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN
37 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 * This code follows the "Whitesmiths style" C indentation rules. Plenty of discussion
41 * on C indentation can be found on the web, such as <http://www.kafejo.com/komp/1tbs.htm>,
42 * but for the sake of brevity here I will say just this: Curly braces are not syntactially
43 * part of an "if" statement; they are the beginning and ending markers of a compound statement;
44 * therefore common sense dictates that if they are part of a compound statement then they
45 * should be indented to the same level as everything else in that compound statement.
46 * Indenting curly braces at the same level as the "if" implies that curly braces are
47 * part of the "if", which is false. (This is as misleading as people who write "char* x,y;"
48 * thinking that variables x and y are both of type "char*" -- and anyone who doesn't
49 * understand why variable y is not of type "char*" just proves the point that poor code
50 * layout leads people to unfortunate misunderstandings about how the C language really works.)
52 To build this tool, copy and paste the following into a command line:
55 gcc dns-sd.c -o dns-sd
58 gcc dns-sd.c -o dns-sd -I../mDNSShared -ldns_sd
61 cl dns-sd.c -I../mDNSShared -DNOT_HAVE_GETOPT ws2_32.lib ..\mDNSWindows\DLL\Release\dnssd.lib
62 (may require that you run a Visual Studio script such as vsvars32.bat first)
67 #include <stdio.h> // For stdout, stderr
68 #include <stdlib.h> // For exit()
69 #include <string.h> // For strlen(), strcpy(), bzero()
70 #include <errno.h> // For errno, EINTR
72 #include <sys/types.h> // For u_char
79 #define getpid _getpid
80 #define strcasecmp _stricmp
81 #define snprintf _snprintf
83 #include <unistd.h> // For getopt() and optind
84 #include <netdb.h> // For getaddrinfo()
85 #include <sys/time.h> // For struct timeval
86 #include <arpa/inet.h> // For inet_addr()
87 #include <netinet/in.h> // For struct sockaddr_in()
88 #include <sys/socket.h> // For AF_INET
92 //*************************************************************************************************************
95 typedef union { unsigned char b
[2]; unsigned short NotAnInteger
; } Opaque16
;
98 static uint32_t opinterface
= kDNSServiceInterfaceIndexAny
;
99 static DNSServiceRef client
= NULL
;
100 static DNSServiceRef client2
= NULL
;
101 static int num_printed
;
102 static char addtest
= 0;
103 static DNSRecordRef record
= NULL
;
104 static char myhinfoW
[14] = "\002PC\012Windows XP";
105 static char myhinfoX
[ 9] = "\003Mac\004OS X";
106 static char updatetest
[3] = "\002AA";
107 static char bigNULL
[4096];
109 // Note: the select() implementation on Windows (Winsock2) fails with any timeout much larger than this
110 #define LONG_TIME 100000000
112 static volatile int stopNow
= 0;
113 static volatile int timeOut
= LONG_TIME
;
115 //*************************************************************************************************************
116 // Supporting Utility Function
118 static uint16_t GetRRType(const char *s
)
120 if (!strcasecmp(s
, "A" )) return(kDNSServiceType_A
);
121 else if (!strcasecmp(s
, "NS" )) return(kDNSServiceType_NS
);
122 else if (!strcasecmp(s
, "MD" )) return(kDNSServiceType_MD
);
123 else if (!strcasecmp(s
, "MF" )) return(kDNSServiceType_MF
);
124 else if (!strcasecmp(s
, "CNAME" )) return(kDNSServiceType_CNAME
);
125 else if (!strcasecmp(s
, "SOA" )) return(kDNSServiceType_SOA
);
126 else if (!strcasecmp(s
, "MB" )) return(kDNSServiceType_MB
);
127 else if (!strcasecmp(s
, "MG" )) return(kDNSServiceType_MG
);
128 else if (!strcasecmp(s
, "MR" )) return(kDNSServiceType_MR
);
129 else if (!strcasecmp(s
, "NULL" )) return(kDNSServiceType_NULL
);
130 else if (!strcasecmp(s
, "WKS" )) return(kDNSServiceType_WKS
);
131 else if (!strcasecmp(s
, "PTR" )) return(kDNSServiceType_PTR
);
132 else if (!strcasecmp(s
, "HINFO" )) return(kDNSServiceType_HINFO
);
133 else if (!strcasecmp(s
, "MINFO" )) return(kDNSServiceType_MINFO
);
134 else if (!strcasecmp(s
, "MX" )) return(kDNSServiceType_MX
);
135 else if (!strcasecmp(s
, "TXT" )) return(kDNSServiceType_TXT
);
136 else if (!strcasecmp(s
, "RP" )) return(kDNSServiceType_RP
);
137 else if (!strcasecmp(s
, "AFSDB" )) return(kDNSServiceType_AFSDB
);
138 else if (!strcasecmp(s
, "X25" )) return(kDNSServiceType_X25
);
139 else if (!strcasecmp(s
, "ISDN" )) return(kDNSServiceType_ISDN
);
140 else if (!strcasecmp(s
, "RT" )) return(kDNSServiceType_RT
);
141 else if (!strcasecmp(s
, "NSAP" )) return(kDNSServiceType_NSAP
);
142 else if (!strcasecmp(s
, "NSAP_PTR")) return(kDNSServiceType_NSAP_PTR
);
143 else if (!strcasecmp(s
, "SIG" )) return(kDNSServiceType_SIG
);
144 else if (!strcasecmp(s
, "KEY" )) return(kDNSServiceType_KEY
);
145 else if (!strcasecmp(s
, "PX" )) return(kDNSServiceType_PX
);
146 else if (!strcasecmp(s
, "GPOS" )) return(kDNSServiceType_GPOS
);
147 else if (!strcasecmp(s
, "AAAA" )) return(kDNSServiceType_AAAA
);
148 else if (!strcasecmp(s
, "LOC" )) return(kDNSServiceType_LOC
);
149 else if (!strcasecmp(s
, "NXT" )) return(kDNSServiceType_NXT
);
150 else if (!strcasecmp(s
, "EID" )) return(kDNSServiceType_EID
);
151 else if (!strcasecmp(s
, "NIMLOC" )) return(kDNSServiceType_NIMLOC
);
152 else if (!strcasecmp(s
, "SRV" )) return(kDNSServiceType_SRV
);
153 else if (!strcasecmp(s
, "ATMA" )) return(kDNSServiceType_ATMA
);
154 else if (!strcasecmp(s
, "NAPTR" )) return(kDNSServiceType_NAPTR
);
155 else if (!strcasecmp(s
, "KX" )) return(kDNSServiceType_KX
);
156 else if (!strcasecmp(s
, "CERT" )) return(kDNSServiceType_CERT
);
157 else if (!strcasecmp(s
, "A6" )) return(kDNSServiceType_A6
);
158 else if (!strcasecmp(s
, "DNAME" )) return(kDNSServiceType_DNAME
);
159 else if (!strcasecmp(s
, "SINK" )) return(kDNSServiceType_SINK
);
160 else if (!strcasecmp(s
, "OPT" )) return(kDNSServiceType_OPT
);
161 else if (!strcasecmp(s
, "TKEY" )) return(kDNSServiceType_TKEY
);
162 else if (!strcasecmp(s
, "TSIG" )) return(kDNSServiceType_TSIG
);
163 else if (!strcasecmp(s
, "IXFR" )) return(kDNSServiceType_IXFR
);
164 else if (!strcasecmp(s
, "AXFR" )) return(kDNSServiceType_AXFR
);
165 else if (!strcasecmp(s
, "MAILB" )) return(kDNSServiceType_MAILB
);
166 else if (!strcasecmp(s
, "MAILA" )) return(kDNSServiceType_MAILA
);
167 else if (!strcasecmp(s
, "ANY" )) return(kDNSServiceType_ANY
);
168 else return(atoi(s
));
171 //*************************************************************************************************************
172 // Sample callback functions for each of the operation types
174 static void printtimestamp(void)
180 time_t uct
= time(NULL
);
181 tm
= *localtime(&uct
);
182 GetLocalTime(&sysTime
);
183 ms
= sysTime
.wMilliseconds
;
186 gettimeofday(&tv
, NULL
);
187 localtime_r((time_t*)&tv
.tv_sec
, &tm
);
188 ms
= tv
.tv_usec
/1000;
190 printf("%2d:%02d:%02d.%03d ", tm
.tm_hour
, tm
.tm_min
, tm
.tm_sec
, ms
);
193 #define DomainMsg(X) (((X) & kDNSServiceFlagsDefault) ? "(Default)" : \
194 ((X) & kDNSServiceFlagsAdd) ? "Added" : "Removed")
196 static const char *GetNextLabel(const char *cstr
, char label
[64])
199 while (*cstr
&& *cstr
!= '.') // While we have characters in the label...
205 if (isdigit(cstr
[-1]) && isdigit(cstr
[0]) && isdigit(cstr
[1]))
207 int v0
= cstr
[-1] - '0'; // then interpret as three-digit decimal
208 int v1
= cstr
[ 0] - '0';
209 int v2
= cstr
[ 1] - '0';
210 int val
= v0
* 100 + v1
* 10 + v2
;
211 if (val
<= 255) { c
= (char)val
; cstr
+= 2; } // If valid three-digit decimal value, use it
215 if (ptr
>= label
+64) return(NULL
);
217 if (*cstr
) cstr
++; // Skip over the trailing dot (if present)
222 static void DNSSD_API
enum_reply(DNSServiceRef client
, const DNSServiceFlags flags
, uint32_t ifIndex
,
223 DNSServiceErrorType errorCode
, const char *replyDomain
, void *context
)
225 DNSServiceFlags partialflags
= flags
& ~(kDNSServiceFlagsMoreComing
| kDNSServiceFlagsAdd
| kDNSServiceFlagsDefault
);
226 int labels
= 0, depth
= 0, i
, initial
= 0;
228 const char *label
[128];
230 (void)client
; // Unused
231 (void)ifIndex
; // Unused
232 (void)errorCode
; // Unused
233 (void)context
; // Unused
235 if (!*replyDomain
) return;
237 // 1. Print the header
238 if (num_printed
++ == 0) printf("Timestamp Recommended %s domain\n", operation
== 'E' ? "Registration" : "Browsing");
240 printf("%-10s", DomainMsg(flags
));
241 printf("%-8s", (flags
& kDNSServiceFlagsMoreComing
) ? "(More)" : "");
242 if (partialflags
) printf("Flags: %4X ", partialflags
);
245 // 2. Count the labels
248 label
[labels
++] = replyDomain
;
249 replyDomain
= GetNextLabel(replyDomain
, text
);
252 // 3. Decide if we're going to clump the last two or three labels (e.g. "apple.com", or "nicta.com.au")
253 if (labels
>= 3 && replyDomain
- label
[labels
-1] <= 3 && label
[labels
-1] - label
[labels
-2] <= 4) initial
= 3;
254 else if (labels
>= 2 && replyDomain
- label
[labels
-1] <= 4) initial
= 2;
258 // 4. Print the initial one-, two- or three-label clump
259 for (i
=0; i
<initial
; i
++)
261 GetNextLabel(label
[labels
+i
], text
);
262 if (i
>0) printf(".");
267 // 5. Print the remainder of the hierarchy
268 for (depth
=0; depth
<labels
; depth
++)
271 for (i
=0; i
<=depth
; i
++) printf("- ");
272 GetNextLabel(label
[labels
-1-depth
], text
);
273 printf("> %s\n", text
);
276 if (!(flags
& kDNSServiceFlagsMoreComing
)) fflush(stdout
);
279 static void DNSSD_API
browse_reply(DNSServiceRef client
, const DNSServiceFlags flags
, uint32_t ifIndex
, DNSServiceErrorType errorCode
,
280 const char *replyName
, const char *replyType
, const char *replyDomain
, void *context
)
282 char *op
= (flags
& kDNSServiceFlagsAdd
) ? "Add" : "Rmv";
283 (void)client
; // Unused
284 (void)errorCode
; // Unused
285 (void)context
; // Unused
286 if (num_printed
++ == 0) printf("Timestamp A/R Flags if %-25s %-25s %s\n", "Domain", "Service Type", "Instance Name");
288 printf("%s%6X%3d %-25s %-25s %s\n", op
, flags
, ifIndex
, replyDomain
, replyType
, replyName
);
289 if (!(flags
& kDNSServiceFlagsMoreComing
)) fflush(stdout
);
292 static void DNSSD_API
resolve_reply(DNSServiceRef client
, const DNSServiceFlags flags
, uint32_t ifIndex
, DNSServiceErrorType errorCode
,
293 const char *fullname
, const char *hosttarget
, uint16_t opaqueport
, uint16_t txtLen
, const char *txtRecord
, void *context
)
295 union { uint16_t s
; u_char b
[2]; } port
= { opaqueport
};
296 uint16_t PortAsNumber
= ((uint16_t)port
.b
[0]) << 8 | port
.b
[1];
298 (void)client
; // Unused
299 (void)ifIndex
; // Unused
300 (void)errorCode
; // Unused
301 (void)context
; // Unused
304 printf("%s can be reached at %s:%u", fullname
, hosttarget
, PortAsNumber
);
306 if (flags
) printf(" Flags: %X", flags
);
307 if (txtLen
> 1) // Don't show degenerate TXT records containing nothing but a single empty string
309 const char *ptr
= txtRecord
;
310 const char *max
= txtRecord
+ txtLen
;
314 const char *end
= ptr
+ 1 + ptr
[0];
315 if (end
> max
) { printf("<< invalid data >>"); break; }
316 if (++ptr
< end
) printf(" "); // As long as string is non-empty, begin with a space
319 if (*ptr
== '\\') printf("\\\\"); // '\' displays as "\\"
320 else if (*ptr
== ' ' ) printf("\\ "); // ' ' displays as "\ "
321 else if (*ptr
> ' ' ) printf("%c", *ptr
); // Display normal characters as-is
322 else printf("\\x%02X", *ptr
); // ther chararacters displayed as "\xHH"
328 if (!(flags
& kDNSServiceFlagsMoreComing
)) fflush(stdout
);
331 static void myTimerCallBack(void)
333 DNSServiceErrorType err
= kDNSServiceErr_Unknown
;
341 case 0: printf("Adding Test HINFO record\n");
342 err
= DNSServiceAddRecord(client
, &record
, 0, kDNSServiceType_HINFO
, sizeof(myhinfoW
), &myhinfoW
[0], 0);
345 case 1: printf("Updating Test HINFO record\n");
346 err
= DNSServiceUpdateRecord(client
, record
, 0, sizeof(myhinfoX
), &myhinfoX
[0], 0);
349 case 2: printf("Removing Test HINFO record\n");
350 err
= DNSServiceRemoveRecord(client
, record
, 0);
359 if (updatetest
[1] != 'Z') updatetest
[1]++;
360 else updatetest
[1] = 'A';
361 updatetest
[0] = 3 - updatetest
[0];
362 updatetest
[2] = updatetest
[1];
363 printf("Updating Test TXT record to %c\n", updatetest
[1]);
364 err
= DNSServiceUpdateRecord(client
, NULL
, 0, 1+updatetest
[0], &updatetest
[0], 0);
370 printf("Adding big NULL record\n");
371 err
= DNSServiceAddRecord(client
, &record
, 0, kDNSServiceType_NULL
, sizeof(bigNULL
), &bigNULL
[0], 0);
377 if (err
!= kDNSServiceErr_NoError
)
379 fprintf(stderr
, "DNSService call failed %ld\n", (long int)err
);
384 static void DNSSD_API
reg_reply(DNSServiceRef client
, const DNSServiceFlags flags
, DNSServiceErrorType errorCode
,
385 const char *name
, const char *regtype
, const char *domain
, void *context
)
387 (void)client
; // Unused
388 (void)flags
; // Unused
389 (void)context
; // Unused
391 printf("Got a reply for %s.%s%s: ", name
, regtype
, domain
);
394 case kDNSServiceErr_NoError
: printf("Name now registered and active\n"); break;
395 case kDNSServiceErr_NameConflict
: printf("Name in use, please choose another\n"); exit(-1);
396 default: printf("Error %d\n", errorCode
); return;
399 if (operation
== 'A' || operation
== 'U' || operation
== 'N') timeOut
= 5;
400 if (!(flags
& kDNSServiceFlagsMoreComing
)) fflush(stdout
);
403 static void DNSSD_API
qr_reply(DNSServiceRef sdRef
, const DNSServiceFlags flags
, uint32_t ifIndex
, DNSServiceErrorType errorCode
,
404 const char *fullname
, uint16_t rrtype
, uint16_t rrclass
, uint16_t rdlen
, const void *rdata
, uint32_t ttl
, void *context
)
406 char *op
= (flags
& kDNSServiceFlagsAdd
) ? "Add" : "Rmv";
407 const unsigned char *rd
= rdata
;
408 const unsigned char *end
= (const unsigned char *) rdata
+ rdlen
;
411 const char * const lim
= rdb
+ sizeof(rdb
);
413 (void)sdRef
; // Unused
414 (void)flags
; // Unused
415 (void)ifIndex
; // Unused
416 (void)errorCode
;// Unused
418 (void)context
; // Unused
422 case kDNSServiceType_A
: sprintf(rdb
, "%d.%d.%d.%d", rd
[0], rd
[1], rd
[2], rd
[3]); break;
423 default : p
+= snprintf(p
, lim
-p
, "%d bytes%s", rdlen
, rdlen
? ":" : "");
424 while (rd
< end
&& p
< lim
) p
+= snprintf(p
, lim
-p
, " %02X", *rd
++);
427 if (num_printed
++ == 0) printf("Timestamp A/R Flags if %-30s%4s%4s Rdata\n", "Name", "T", "C");
429 printf("%s%6X%3d %-30s%4d%4d %s\n", op
, flags
, ifIndex
, fullname
, rrtype
, rrclass
, rdb
);
430 if (!(flags
& kDNSServiceFlagsMoreComing
)) fflush(stdout
);
433 //*************************************************************************************************************
434 // The main test function
436 static void HandleEvents(void)
438 int dns_sd_fd
= client
? DNSServiceRefSockFD(client
) : -1;
439 int dns_sd_fd2
= client2
? DNSServiceRefSockFD(client2
) : -1;
440 int nfds
= dns_sd_fd
+ 1;
445 if (dns_sd_fd2
> dns_sd_fd
) nfds
= dns_sd_fd2
+ 1;
449 // 1. Set up the fd_set as usual here.
450 // This example client has no file descriptors of its own,
451 // but a real application would call FD_SET to add them to the set here
454 // 2. Add the fd for our client(s) to the fd_set
455 if (client
) FD_SET(dns_sd_fd
, &readfds
);
456 if (client2
) FD_SET(dns_sd_fd2
, &readfds
);
458 // 3. Set up the timeout.
462 result
= select(nfds
, &readfds
, (fd_set
*)NULL
, (fd_set
*)NULL
, &tv
);
465 DNSServiceErrorType err
= kDNSServiceErr_NoError
;
466 if (client
&& FD_ISSET(dns_sd_fd
, &readfds
)) err
= DNSServiceProcessResult(client
);
467 else if (client2
&& FD_ISSET(dns_sd_fd2
, &readfds
)) err
= DNSServiceProcessResult(client2
);
468 if (err
) { fprintf(stderr
, "DNSServiceProcessResult returned %d\n", err
); stopNow
= 1; }
470 else if (result
== 0)
474 printf("select() returned %d errno %d %s\n", result
, errno
, strerror(errno
));
475 if (errno
!= EINTR
) stopNow
= 1;
480 static int getfirstoption( int argc
, char **argv
, const char *optstr
, int *pOptInd
)
481 // Return the recognized option in optstr and the option index of the next arg.
485 for ( i
=1; i
< argc
; i
++)
487 if ( argv
[i
][0] == '-' && &argv
[i
][1] &&
488 NULL
!= strchr( optstr
, argv
[i
][1]))
498 int operation
= getopt(argc
, (char * const *)argv
, optstr
);
504 static void DNSSD_API
MyRegisterRecordCallback(DNSServiceRef service
, DNSRecordRef record
, const DNSServiceFlags flags
,
505 DNSServiceErrorType errorCode
, void * context
)
507 char *name
= (char *)context
;
509 (void)service
; // Unused
510 (void)record
; // Unused
511 (void)flags
; // Unused
513 printf("Got a reply for %s: ", name
);
516 case kDNSServiceErr_NoError
: printf("Name now registered and active\n"); break;
517 case kDNSServiceErr_NameConflict
: printf("Name in use, please choose another\n"); exit(-1);
518 default: printf("Error %d\n", errorCode
); return;
520 if (!(flags
& kDNSServiceFlagsMoreComing
)) fflush(stdout
);
523 static unsigned long getip(const char *const name
)
525 unsigned long ip
= 0;
526 struct addrinfo hints
;
527 struct addrinfo
* addrs
= NULL
;
529 memset(&hints
, 0, sizeof(hints
));
530 hints
.ai_family
= AF_INET
;
532 if (getaddrinfo(name
, NULL
, &hints
, &addrs
) == 0)
534 ip
= ((struct sockaddr_in
*) addrs
->ai_addr
)->sin_addr
.s_addr
;
545 static DNSServiceErrorType
RegisterProxyAddressRecord(DNSServiceRef
*sdRef
, const char *host
, const char *ip
)
547 // Call getip() after the call DNSServiceCreateConnection(). On the Win32 platform, WinSock must
548 // be initialized for getip() to succeed. Any DNSService* call will initialize WinSock for us,
549 // so make sure DNSServiceCreateConnection() is called before getip() is.
550 unsigned long addr
= 0;
551 DNSServiceErrorType err
= DNSServiceCreateConnection(sdRef
);
552 if (err
) { fprintf(stderr
, "DNSServiceCreateConnection returned %d\n", err
); return(err
); }
554 return(DNSServiceRegisterRecord(*sdRef
, &record
, kDNSServiceFlagsUnique
, kDNSServiceInterfaceIndexAny
, host
,
555 kDNSServiceType_A
, kDNSServiceClass_IN
, sizeof(addr
), &addr
, 240, MyRegisterRecordCallback
, (void*)host
));
556 // Note, should probably add support for creating proxy AAAA records too, one day
559 static DNSServiceErrorType
RegisterService(DNSServiceRef
*sdRef
,
560 const char *nam
, const char *typ
, const char *dom
, const char *host
, const char *port
, int argc
, char **argv
)
562 uint16_t PortAsNumber
= atoi(port
);
563 Opaque16 registerPort
= { { PortAsNumber
>> 8, PortAsNumber
& 0xFF } };
564 unsigned char txt
[2048] = "";
565 unsigned char *ptr
= txt
;
568 if (nam
[0] == '.' && nam
[1] == 0) nam
= ""; // We allow '.' on the command line as a synonym for empty string
569 if (dom
[0] == '.' && dom
[1] == 0) dom
= ""; // We allow '.' on the command line as a synonym for empty string
571 printf("Registering Service %s.%s%s%s", nam
[0] ? nam
: "<<Default>>", typ
, dom
[0] ? "." : "", dom
);
572 if (host
&& *host
) printf(" host %s", host
);
573 printf(" port %s\n", port
);
575 for (i
= 0; i
< argc
; i
++)
577 int length
= strlen(argv
[i
]);
580 *ptr
++ = (unsigned char)length
;
581 strcpy((char*)ptr
, argv
[i
]);
583 printf("TXT %s\n", argv
[i
]);
587 return(DNSServiceRegister(sdRef
, /* kDNSServiceFlagsAllowRemoteQuery */ 0, opinterface
, nam
, typ
, dom
, host
, registerPort
.NotAnInteger
, (uint16_t) (ptr
-txt
), txt
, reg_reply
, NULL
));
590 int main(int argc
, char **argv
)
593 const char kFilePathSep
= '\\';
595 const char kFilePathSep
= '/';
597 DNSServiceErrorType err
;
600 const char *progname
= strrchr(argv
[0], kFilePathSep
) ? strrchr(argv
[0], kFilePathSep
) + 1 : argv
[0];
602 if (argc
> 1 && !strcmp(argv
[1], "-lo"))
606 opinterface
= kDNSServiceInterfaceIndexLocalOnly
;
607 printf("Using LocalOnly\n");
610 if (argc
> 2 && !strcmp(argv
[1], "-i") && atoi(argv
[2]))
612 opinterface
= atoi(argv
[2]);
615 printf("Using interface %d\n", opinterface
);
618 if (argc
< 2) goto Fail
; // Minimum command line is the command name and one argument
619 operation
= getfirstoption( argc
, argv
, "EFBLQRPAUNTMI", &optind
);
620 if (operation
== -1) goto Fail
;
624 case 'E': printf("Looking for recommended registration domains:\n");
625 err
= DNSServiceEnumerateDomains(&client
, kDNSServiceFlagsRegistrationDomains
, opinterface
, enum_reply
, NULL
);
628 case 'F': printf("Looking for recommended browsing domains:\n");
629 err
= DNSServiceEnumerateDomains(&client
, kDNSServiceFlagsBrowseDomains
, opinterface
, enum_reply
, NULL
);
630 //enum_reply(client, kDNSServiceFlagsAdd, 0, 0, "nicta.com.au.", NULL);
631 //enum_reply(client, kDNSServiceFlagsAdd, 0, 0, "bonjour.nicta.com.au.", NULL);
632 //enum_reply(client, kDNSServiceFlagsAdd, 0, 0, "ibm.com.", NULL);
633 //enum_reply(client, kDNSServiceFlagsAdd, 0, 0, "dns-sd.ibm.com.", NULL);
636 case 'B': if (argc
< optind
+1) goto Fail
;
637 dom
= (argc
< optind
+2) ? "" : argv
[optind
+1];
638 if (dom
[0] == '.' && dom
[1] == 0) dom
[0] = 0; // We allow '.' on the command line as a synonym for empty string
639 printf("Browsing for %s%s%s\n", argv
[optind
+0], dom
[0] ? "." : "", dom
);
640 err
= DNSServiceBrowse(&client
, 0, opinterface
, argv
[optind
+0], dom
, browse_reply
, NULL
);
643 case 'L': if (argc
< optind
+2) goto Fail
;
644 dom
= (argc
< optind
+3) ? "local" : argv
[optind
+2];
645 if (dom
[0] == '.' && dom
[1] == 0) dom
= "local"; // We allow '.' on the command line as a synonym for "local"
646 printf("Lookup %s.%s.%s\n", argv
[optind
+0], argv
[optind
+1], dom
);
647 err
= DNSServiceResolve(&client
, 0, opinterface
, argv
[optind
+0], argv
[optind
+1], dom
, resolve_reply
, NULL
);
650 case 'R': if (argc
< optind
+4) goto Fail
;
651 err
= RegisterService(&client
, argv
[optind
+0], argv
[optind
+1], argv
[optind
+2], NULL
, argv
[optind
+3], argc
-(optind
+4), argv
+(optind
+4));
654 case 'P': if (argc
< optind
+6) goto Fail
;
655 err
= RegisterProxyAddressRecord(&client2
, argv
[optind
+4], argv
[optind
+5]);
657 err
= RegisterService(&client
, argv
[optind
+0], argv
[optind
+1], argv
[optind
+2], argv
[optind
+4], argv
[optind
+3], argc
-(optind
+6), argv
+(optind
+6));
661 uint16_t rrtype
, rrclass
;
662 DNSServiceFlags flags
= 0;
663 if (argc
< optind
+1) goto Fail
;
664 rrtype
= (argc
<= optind
+1) ? kDNSServiceType_A
: GetRRType(argv
[optind
+1]);
665 rrclass
= (argc
<= optind
+2) ? kDNSServiceClass_IN
: atoi(argv
[optind
+2]);
666 if (rrtype
== kDNSServiceType_TXT
|| rrtype
== kDNSServiceType_PTR
) flags
|= kDNSServiceFlagsLongLivedQuery
;
667 err
= DNSServiceQueryRecord(&client
, flags
, opinterface
, argv
[optind
+0], rrtype
, rrclass
, qr_reply
, NULL
);
674 Opaque16 registerPort
= { { 0x12, 0x34 } };
675 static const char TXT
[] = "\xC" "First String" "\xD" "Second String" "\xC" "Third String";
676 printf("Registering Service Test._testupdate._tcp.local.\n");
677 err
= DNSServiceRegister(&client
, 0, opinterface
, "Test", "_testupdate._tcp.", "", NULL
, registerPort
.NotAnInteger
, sizeof(TXT
)-1, TXT
, reg_reply
, NULL
);
682 Opaque16 registerPort
= { { 0x23, 0x45 } };
685 for (i
=0; i
<sizeof(TXT
); i
++)
686 if ((i
& 0x1F) == 0) TXT
[i
] = 0x1F; else TXT
[i
] = 'A' + (i
>> 5);
687 printf("Registering Service Test._testlargetxt._tcp.local.\n");
688 err
= DNSServiceRegister(&client
, 0, opinterface
, "Test", "_testlargetxt._tcp.", "", NULL
, registerPort
.NotAnInteger
, sizeof(TXT
), TXT
, reg_reply
, NULL
);
693 pid_t pid
= getpid();
694 Opaque16 registerPort
= { { pid
>> 8, pid
& 0xFF } };
695 static const char TXT1
[] = "\xC" "First String" "\xD" "Second String" "\xC" "Third String";
696 static const char TXT2
[] = "\xD" "Fourth String" "\xC" "Fifth String" "\xC" "Sixth String";
697 printf("Registering Service Test._testdualtxt._tcp.local.\n");
698 err
= DNSServiceRegister(&client
, 0, opinterface
, "Test", "_testdualtxt._tcp.", "", NULL
, registerPort
.NotAnInteger
, sizeof(TXT1
)-1, TXT1
, reg_reply
, NULL
);
699 if (!err
) err
= DNSServiceAddRecord(client
, &record
, 0, kDNSServiceType_TXT
, sizeof(TXT2
)-1, TXT2
, 0);
704 pid_t pid
= getpid();
705 Opaque16 registerPort
= { { pid
>> 8, pid
& 0xFF } };
706 static const char TXT
[] = "\x09" "Test Data";
707 printf("Registering Service Test._testtxt._tcp.local.\n");
708 err
= DNSServiceRegister(&client
, 0, opinterface
, "Test", "_testtxt._tcp.", "", NULL
, registerPort
.NotAnInteger
, 0, NULL
, reg_reply
, NULL
);
709 if (!err
) err
= DNSServiceUpdateRecord(client
, NULL
, 0, sizeof(TXT
)-1, TXT
, 0);
716 if (!client
|| err
!= kDNSServiceErr_NoError
) { fprintf(stderr
, "DNSService call failed %ld\n", (long int)err
); return (-1); }
719 // Be sure to deallocate the DNSServiceRef when you're finished
720 if (client
) DNSServiceRefDeallocate(client
);
721 if (client2
) DNSServiceRefDeallocate(client2
);
725 fprintf(stderr
, "%s -E (Enumerate recommended registration domains)\n", progname
);
726 fprintf(stderr
, "%s -F (Enumerate recommended browsing domains)\n", progname
);
727 fprintf(stderr
, "%s -B <Type> <Domain> (Browse for services instances)\n", progname
);
728 fprintf(stderr
, "%s -L <Name> <Type> <Domain> (Look up a service instance)\n", progname
);
729 fprintf(stderr
, "%s -R <Name> <Type> <Domain> <Port> [<TXT>...] (Register a service)\n", progname
);
730 fprintf(stderr
, "%s -P <Name> <Type> <Domain> <Port> <Host> <IP> [<TXT>...] (Proxy)\n", progname
);
731 fprintf(stderr
, "%s -Q <FQDN> <rrtype> <rrclass> (Generic query for any record type)\n", progname
);
732 fprintf(stderr
, "%s -A (Test Adding/Updating/Deleting a record)\n", progname
);
733 fprintf(stderr
, "%s -U (Test updating a TXT record)\n", progname
);
734 fprintf(stderr
, "%s -N (Test adding a large NULL record)\n", progname
);
735 fprintf(stderr
, "%s -T (Test creating a large TXT record)\n", progname
);
736 fprintf(stderr
, "%s -M (Test creating a registration with multiple TXT records)\n", progname
);
737 fprintf(stderr
, "%s -I (Test registering and then immediately updating TXT record)\n", progname
);