• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.net.mdns (mDNS Management)
2
3Multicast DNS (mDNS) provides functions such as adding, removing, discovering, and resolving local services on a LAN.
4
5> **NOTE**
6> The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version.
7
8## Modules to Import
9
10```ts
11import mdns from '@ohos.net.mdns'
12```
13
14## mdns.addLocalService<sup>10+</sup>
15
16addLocalService(context: Context, serviceInfo: LocalServiceInfo, callback: AsyncCallback\<LocalServiceInfo>): void
17
18Adds an mDNS service. This API uses an asynchronous callback to return the result.
19
20**System capability**: SystemCapability.Communication.NetManager.MDNS
21
22**Parameters**
23
24| Name       | Type                            | Mandatory| Description                                    |
25|-------------|----------------------------------|-----------|-------------------------------------------------|
26| context     | Context                          | Yes      | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-app-ability-uiAbility.md).|
27| serviceInfo | [LocalServiceInfo](#localserviceinfo)                 | Yes       |   mDNS service information.     |
28| callback | AsyncCallback\<[LocalServiceInfo](#localserviceinfo)> | Yes       |   Callback used to return the result. If the operation is successful, **error** is **undefined** and **data** is the mDNS service information.     |
29
30**Error codes**
31
32| ID     | Error Message|
33|---------|---|
34| 401     | Parameter error. |
35| 2100002 | Operation failed. Cannot connect to service. |
36| 2100003 | System internal error. |
37| 2204003 | Callback duplicated. |
38| 2204008 | Service instance duplicated. |
39| 2204010 | Send packet failed. |
40
41> **NOTE**
42> For details about the error codes, see [mDNS Error Codes](../errorcodes/errorcode-net-mdns.md).
43
44**Example**
45
46Stage model:
47
48```ts
49// Obtain the context.
50import mdns from '@ohos.net.mdns'
51import UIAbility from '@ohos.app.ability.UIAbility';
52import { BusinessError } from '@ohos.base';
53import window from '@ohos.window';
54
55export class GlobalContext {
56  private constructor() {}
57  private static instance: GlobalContext;
58  private _objects = new Map<string, Object>();
59
60  public static getContext(): GlobalContext {
61    if (!GlobalContext.instance) {
62      GlobalContext.instance = new GlobalContext();
63    }
64    return GlobalContext.instance;
65  }
66
67  getObject(value: string): Object | undefined {
68    return this._objects.get(value);
69  }
70
71  setObject(key: string, objectClass: Object): void {
72    this._objects.set(key, objectClass);
73  }
74}
75
76class EntryAbility extends UIAbility {
77  value:number = 0;
78  onWindowStageCreate(windowStage:window.WindowStage): void{
79    GlobalContext.getContext().setObject("value", this.value);
80  }
81}
82let context = GlobalContext.getContext().getObject("value");
83
84let localServiceInfo: mdns.LocalServiceInfo = {
85  serviceType: "_print._tcp",
86  serviceName: "servicename",
87  port: 5555,
88  host: {
89  address: "10.14.**.***",
90  },
91  serviceAttribute: [{key: "111", value: [1]}]
92}
93
94mdns.addLocalService(context as Context, localServiceInfo, (error:BusinessError, data:mdns.LocalServiceInfo) =>  {
95  console.log(JSON.stringify(error));
96  console.log(JSON.stringify(data));
97});
98```
99
100## mdns.addLocalService<sup>10+</sup>
101
102addLocalService(context: Context, serviceInfo: LocalServiceInfo): Promise\<LocalServiceInfo>
103
104Adds an mDNS service. This API uses a promise to return the result.
105
106**System capability**: SystemCapability.Communication.NetManager.MDNS
107
108**Parameters**
109
110| Name       | Type                            | Mandatory| Description                                    |
111|-------------|----------------------------------|-----------|-------------------------------------------------|
112| context     | Context                          | Yes      | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-app-ability-uiAbility.md).|
113| serviceInfo | [LocalServiceInfo](#localserviceinfo)                 | Yes       |   mDNS service information.     |
114
115**Return value**
116
117| Type                             | Description                                 |
118| --------------------------------- | ------------------------------------- |
119| Promise\<[LocalServiceInfo](#localserviceinfo)> | Promise used to return the result.|
120
121**Error codes**
122
123| ID     | Error Message|
124|---------|---|
125| 401     | Parameter error. |
126| 2100002 | Operation failed. Cannot connect to service. |
127| 2100003 | System internal error. |
128| 2204003 | Callback duplicated. |
129| 2204008 | Service instance duplicated. |
130| 2204010 | Send packet failed. |
131
132> **NOTE**
133> For details about the error codes, see [mDNS Error Codes](../errorcodes/errorcode-net-mdns.md).
134
135**Example**
136
137Stage model:
138
139```ts
140// Obtain the context.
141import mdns from '@ohos.net.mdns'
142import UIAbility from '@ohos.app.ability.UIAbility';
143import { BusinessError } from '@ohos.base';
144import window from '@ohos.window';
145
146export class GlobalContext {
147  private constructor() {}
148  private static instance: GlobalContext;
149  private _objects = new Map<string, Object>();
150
151  public static getContext(): GlobalContext {
152    if (!GlobalContext.instance) {
153      GlobalContext.instance = new GlobalContext();
154    }
155    return GlobalContext.instance;
156  }
157
158  getObject(value: string): Object | undefined {
159    return this._objects.get(value);
160  }
161
162  setObject(key: string, objectClass: Object): void {
163    this._objects.set(key, objectClass);
164  }
165}
166
167class EntryAbility extends UIAbility {
168  value:number = 0;
169  onWindowStageCreate(windowStage:window.WindowStage): void{
170    GlobalContext.getContext().setObject("value", this.value);
171  }
172}
173let context = GlobalContext.getContext().getObject("value");
174
175let localServiceInfo: mdns.LocalServiceInfo = {
176  serviceType: "_print._tcp",
177  serviceName: "servicename",
178  port: 5555,
179  host: {
180    address: "10.14.**.***",
181  },
182  serviceAttribute: [{key: "111", value: [1]}]
183}
184
185mdns.addLocalService(context as Context, localServiceInfo).then((data: mdns.LocalServiceInfo) => {
186  console.log(JSON.stringify(data));
187});
188```
189
190## mdns.removeLocalService<sup>10+</sup>
191
192removeLocalService(context: Context, serviceInfo: LocalServiceInfo, callback: AsyncCallback\<LocalServiceInfo>): void
193
194Removes an mDNS service. This API uses an asynchronous callback to return the result.
195
196**System capability**: SystemCapability.Communication.NetManager.MDNS
197
198**Parameters**
199
200| Name       | Type                            | Mandatory| Description                                    |
201|-------------|----------------------------------|-----------|-------------------------------------------------|
202| context     | Context                          | Yes      | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-app-ability-uiAbility.md).|
203| serviceInfo | [LocalServiceInfo](#localserviceinfo)                 | Yes       |   mDNS service information.     |
204| callback | AsyncCallback\<[LocalServiceInfo](#localserviceinfo)> | Yes       |   Callback used to return the result. If the operation is successful, **error** is **undefined** and **data** is the mDNS service information.     |
205
206**Error codes**
207
208| ID     | Error Message|
209|---------|---|
210| 401     | Parameter error. |
211| 2100002 | Operation failed. Cannot connect to service. |
212| 2100003 | System internal error. |
213| 2204002 | Callback not found. |
214| 2204008 | Service instance not found. |
215| 2204010 | Send packet failed. |
216
217> **NOTE**
218> For details about the error codes, see [mDNS Error Codes](../errorcodes/errorcode-net-mdns.md).
219
220**Example**
221
222Stage model:
223
224```ts
225// Obtain the context.
226import mdns from '@ohos.net.mdns'
227import UIAbility from '@ohos.app.ability.UIAbility';
228import { BusinessError } from '@ohos.base';
229import window from '@ohos.window';
230
231export class GlobalContext {
232  private constructor() {}
233  private static instance: GlobalContext;
234  private _objects = new Map<string, Object>();
235
236  public static getContext(): GlobalContext {
237    if (!GlobalContext.instance) {
238      GlobalContext.instance = new GlobalContext();
239    }
240    return GlobalContext.instance;
241  }
242
243  getObject(value: string): Object | undefined {
244    return this._objects.get(value);
245  }
246
247  setObject(key: string, objectClass: Object): void {
248    this._objects.set(key, objectClass);
249  }
250}
251
252class EntryAbility extends UIAbility {
253  value:number = 0;
254  onWindowStageCreate(windowStage:window.WindowStage): void{
255    GlobalContext.getContext().setObject("value", this.value);
256  }
257}
258let context = GlobalContext.getContext().getObject("value");
259
260let localServiceInfo: mdns.LocalServiceInfo = {
261  serviceType: "_print._tcp",
262  serviceName: "servicename",
263  port: 5555,
264  host: {
265  address: "10.14.**.***",
266  },
267  serviceAttribute: [{key: "111", value: [1]}]
268}
269
270mdns.removeLocalService(context as Context, localServiceInfo, (error: BusinessError, data: mdns.LocalServiceInfo) =>  {
271  console.log(JSON.stringify(error));
272  console.log(JSON.stringify(data));
273});
274```
275
276## mdns.removeLocalService<sup>10+</sup>
277
278removeLocalService(context: Context, serviceInfo: LocalServiceInfo): Promise\<LocalServiceInfo>
279
280Removes an mDNS service. This API uses a promise to return the result.
281
282**System capability**: SystemCapability.Communication.NetManager.MDNS
283
284**Parameters**
285
286| Name       | Type                            | Mandatory| Description                                    |
287|-------------|----------------------------------|-----------|-------------------------------------------------|
288| context     | Context                          | Yes      | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-app-ability-uiAbility.md).|
289| serviceInfo | [LocalServiceInfo](#localserviceinfo)                 | Yes       |   mDNS service information.     |
290
291**Return value**
292
293| Type                             | Description                                 |
294| --------------------------------- | ------------------------------------- |
295| Promise\<[LocalServiceInfo](#localserviceinfo)> | Promise used to return the result.|
296
297**Error codes**
298
299| ID     | Error Message|
300|---------|---|
301| 401     | Parameter error. |
302| 2100002 | Operation failed. Cannot connect to service. |
303| 2100003 | System internal error. |
304| 2204002 | Callback not found. |
305| 2204008 | Service instance not found. |
306| 2204010 | Send packet failed. |
307
308> **NOTE**
309> For details about the error codes, see [mDNS Error Codes](../errorcodes/errorcode-net-mdns.md).
310
311**Example**
312
313Stage model:
314
315```ts
316import mdns from '@ohos.net.mdns'
317// Obtain the context.
318import UIAbility from '@ohos.app.ability.UIAbility';
319import { BusinessError } from '@ohos.base';
320import window from '@ohos.window';
321
322export class GlobalContext {
323  private constructor() {}
324  private static instance: GlobalContext;
325  private _objects = new Map<string, Object>();
326
327  public static getContext(): GlobalContext {
328    if (!GlobalContext.instance) {
329      GlobalContext.instance = new GlobalContext();
330    }
331    return GlobalContext.instance;
332  }
333
334  getObject(value: string): Object | undefined {
335    return this._objects.get(value);
336  }
337
338  setObject(key: string, objectClass: Object): void {
339    this._objects.set(key, objectClass);
340  }
341}
342
343class EntryAbility extends UIAbility {
344  value:number = 0;
345  onWindowStageCreate(windowStage:window.WindowStage): void{
346    GlobalContext.getContext().setObject("value", this.value);
347  }
348}
349let context = GlobalContext.getContext().getObject("value");
350
351let localServiceInfo: mdns.LocalServiceInfo = {
352  serviceType: "_print._tcp",
353  serviceName: "servicename",
354  port: 5555,
355  host: {
356  address: "10.14.**.***",
357  },
358  serviceAttribute: [{key: "111", value: [1]}]
359}
360
361mdns.removeLocalService(context as Context, localServiceInfo).then((data: mdns.LocalServiceInfo) => {
362  console.log(JSON.stringify(data));
363});
364```
365
366## mdns.createDiscoveryService<sup>10+</sup>
367
368createDiscoveryService(context: Context, serviceType: string): DiscoveryService
369
370Creates a **DiscoveryService** object, which is used to discover mDNS services of the specified type.
371
372**System capability**: SystemCapability.Communication.NetManager.MDNS
373
374**Parameters**
375
376| Name       | Type                            | Mandatory| Description                                    |
377|-------------|---------|-----------| ------------------------------------------------------------ |
378| context     | Context                          | Yes      | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-app-ability-uiAbility.md).|
379| serviceType | string  | Yes      | Type of the mDNS services to be discovered.|
380
381**Return value**
382
383| Type                         | Description                     |
384| ----------------------------- |---------------------------------|
385| DiscoveryService | **DiscoveryService** object used to discover mDNS services based on the specified **serviceType** and **Context**.|
386
387**Error codes**
388
389| ID     | Error Message|
390|---------|---|
391| 401     | Parameter error. |
392
393**Example**
394
395Stage model:
396
397```ts
398// Obtain the context.
399import mdns from '@ohos.net.mdns'
400import UIAbility from '@ohos.app.ability.UIAbility';
401import { BusinessError } from '@ohos.base';
402import window from '@ohos.window';
403
404export class GlobalContext {
405  private constructor() {}
406  private static instance: GlobalContext;
407  private _objects = new Map<string, Object>();
408
409  public static getContext(): GlobalContext {
410    if (!GlobalContext.instance) {
411      GlobalContext.instance = new GlobalContext();
412    }
413    return GlobalContext.instance;
414  }
415
416  getObject(value: string): Object | undefined {
417    return this._objects.get(value);
418  }
419
420  setObject(key: string, objectClass: Object): void {
421    this._objects.set(key, objectClass);
422  }
423}
424
425class EntryAbility extends UIAbility {
426  value:number = 0;
427  onWindowStageCreate(windowStage:window.WindowStage): void{
428    GlobalContext.getContext().setObject("value", this.value);
429  }
430}
431let context = GlobalContext.getContext().getObject("value");
432
433let serviceType = "_print._tcp";
434let discoveryService : Object = mdns.createDiscoveryService(context as Context, serviceType);
435```
436
437## mdns.resolveLocalService<sup>10+</sup>
438
439resolveLocalService(context: Context, serviceInfo: LocalServiceInfo, callback: AsyncCallback\<LocalServiceInfo>): void
440
441Resolves an mDNS service. This API uses an asynchronous callback to return the result.
442
443**System capability**: SystemCapability.Communication.NetManager.MDNS
444
445**Parameters**
446
447| Name       | Type                            | Mandatory| Description                                    |
448|-------------|----------------------------------|-----------|-------------------------------------------------------------|
449| context     | Context                          | Yes      | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-app-ability-uiAbility.md).|
450| serviceInfo | [LocalServiceInfo](#localserviceinfo)                 | Yes       |   mDNS service information.     |
451| callback | AsyncCallback\<[LocalServiceInfo](#localserviceinfo)> | Yes       |   Callback used to return the result. If the operation is successful, **error** is **undefined** and **data** is the mDNS service information.     |
452
453**Error codes**
454
455| ID     | Error Message|
456|---------|----------------------------------------------|
457| 401     | Parameter error.                             |
458| 2100002 | Operation failed. Cannot connect to service. |
459| 2100003 | System internal error.                       |
460| 2204003 | Callback duplicated.                         |
461| 2204006 | Request timeout.                |
462| 2204010 | Send packet failed.                          |
463
464> **NOTE**
465> For details about the error codes, see [mDNS Error Codes](../errorcodes/errorcode-net-mdns.md).
466
467**Example**
468
469Stage model:
470
471```ts
472// Obtain the context.
473import mdns from '@ohos.net.mdns'
474import UIAbility from '@ohos.app.ability.UIAbility';
475import { BusinessError } from '@ohos.base';
476import window from '@ohos.window';
477
478export class GlobalContext {
479  private constructor() {}
480  private static instance: GlobalContext;
481  private _objects = new Map<string, Object>();
482
483  public static getContext(): GlobalContext {
484    if (!GlobalContext.instance) {
485      GlobalContext.instance = new GlobalContext();
486    }
487    return GlobalContext.instance;
488  }
489
490  getObject(value: string): Object | undefined {
491    return this._objects.get(value);
492  }
493
494  setObject(key: string, objectClass: Object): void {
495    this._objects.set(key, objectClass);
496  }
497}
498
499class EntryAbility extends UIAbility {
500  value:number = 0;
501  onWindowStageCreate(windowStage:window.WindowStage): void{
502    GlobalContext.getContext().setObject("value", this.value);
503  }
504}
505let context = GlobalContext.getContext().getObject("value");
506
507let localServiceInfo: mdns.LocalServiceInfo = {
508  serviceType: "_print._tcp",
509  serviceName: "servicename",
510  port: 5555,
511  host: {
512  address: "10.14.**.***",
513  },
514  serviceAttribute: [{key: "111", value: [1]}]
515}
516
517mdns.resolveLocalService(context as Context, localServiceInfo, (error: BusinessError, data: mdns.LocalServiceInfo) =>  {
518  console.log(JSON.stringify(error));
519  console.log(JSON.stringify(data));
520});
521```
522
523## mdns.resolveLocalService<sup>10+</sup>
524
525resolveLocalService(context: Context, serviceInfo: LocalServiceInfo): Promise\<LocalServiceInfo>
526
527Resolves an mDNS service. This API uses a promise to return the result.
528
529**System capability**: SystemCapability.Communication.NetManager.MDNS
530
531**Parameters**
532
533| Name       | Type                            | Mandatory| Description                                    |
534|-------------|--------------|-----------|-----------------------------------------------------|
535| context     | Context                          | Yes      | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-app-ability-uiAbility.md).|
536| serviceInfo | [LocalServiceInfo](#localserviceinfo)                 | Yes       |   mDNS service information.     |
537
538**Return value**
539
540| Type                             | Description                                 |
541|----------------------------| ------------------------------------- |
542| Promise\<[LocalServiceInfo](#localserviceinfo)> | Promise used to return the result.|
543
544**Error codes**
545
546| ID     | Error Message|
547|---------|----------------------------------------------|
548| 401     | Parameter error.                             |
549| 2100002 | Operation failed. Cannot connect to service. |
550| 2100003 | System internal error.                       |
551| 2204003 | Callback duplicated.                         |
552| 2204006 | Request timeout.                |
553| 2204010 | Send packet failed.                          |
554
555> **NOTE**
556> For details about the error codes, see [mDNS Error Codes](../errorcodes/errorcode-net-mdns.md).
557
558**Example**
559
560Stage model:
561
562```ts
563// Obtain the context.
564import mdns from '@ohos.net.mdns'
565import UIAbility from '@ohos.app.ability.UIAbility';
566import { BusinessError } from '@ohos.base';
567import window from '@ohos.window';
568
569export class GlobalContext {
570  private constructor() {}
571  private static instance: GlobalContext;
572  private _objects = new Map<string, Object>();
573
574  public static getContext(): GlobalContext {
575    if (!GlobalContext.instance) {
576      GlobalContext.instance = new GlobalContext();
577    }
578    return GlobalContext.instance;
579  }
580
581  getObject(value: string): Object | undefined {
582    return this._objects.get(value);
583  }
584
585  setObject(key: string, objectClass: Object): void {
586    this._objects.set(key, objectClass);
587  }
588}
589
590class EntryAbility extends UIAbility {
591  value:number = 0;
592  onWindowStageCreate(windowStage:window.WindowStage): void{
593    GlobalContext.getContext().setObject("value", this.value);
594  }
595}
596let context = GlobalContext.getContext().getObject("value");
597
598let localServiceInfo: mdns.LocalServiceInfo = {
599  serviceType: "_print._tcp",
600  serviceName: "servicename",
601  port: 5555,
602  host: {
603  address: "10.14.**.***",
604  },
605  serviceAttribute: [{key: "111", value: [1]}]
606}
607
608mdns.resolveLocalService(context as Context, localServiceInfo).then((data: mdns.LocalServiceInfo) => {
609  console.log(JSON.stringify(data));
610});
611```
612## DiscoveryService<sup>10+</sup>
613
614Defines a **DiscoveryService** object for discovering mDNS services of the specified type.
615
616### startSearchingMDNS<sup>10+</sup>
617
618startSearchingMDNS(): void
619
620Searches for mDNS services on the LAN.
621
622**System capability**: SystemCapability.Communication.NetManager.MDNS
623
624**Example**
625
626Stage model:
627
628```ts
629// Obtain the context.
630import mdns from '@ohos.net.mdns'
631import UIAbility from '@ohos.app.ability.UIAbility';
632import { BusinessError } from '@ohos.base';
633import window from '@ohos.window';
634
635export class GlobalContext {
636  private constructor() {}
637  private static instance: GlobalContext;
638  private _objects = new Map<string, Object>();
639
640  public static getContext(): GlobalContext {
641    if (!GlobalContext.instance) {
642      GlobalContext.instance = new GlobalContext();
643    }
644    return GlobalContext.instance;
645  }
646
647  getObject(value: string): Object | undefined {
648    return this._objects.get(value);
649  }
650
651  setObject(key: string, objectClass: Object): void {
652    this._objects.set(key, objectClass);
653  }
654}
655
656class EntryAbility extends UIAbility {
657  value:number = 0;
658  onWindowStageCreate(windowStage:window.WindowStage): void{
659    GlobalContext.getContext().setObject("value", this.value);
660  }
661}
662let context = GlobalContext.getContext().getObject("value");
663let serviceType = "_print._tcp";
664let discoveryService = mdns.createDiscoveryService(context as Context, serviceType);
665discoveryService.startSearchingMDNS();
666```
667
668### stopSearchingMDNS<sup>10+</sup>
669
670stopSearchingMDNS(): void
671
672Stops searching for mDNS services on the LAN.
673
674**System capability**: SystemCapability.Communication.NetManager.MDNS
675
676**Example**
677
678Stage model:
679
680```ts
681// Obtain the context.
682import mdns from '@ohos.net.mdns'
683import UIAbility from '@ohos.app.ability.UIAbility';
684import { BusinessError } from '@ohos.base';
685import window from '@ohos.window';
686
687export class GlobalContext {
688  private constructor() {}
689  private static instance: GlobalContext;
690  private _objects = new Map<string, Object>();
691
692  public static getContext(): GlobalContext {
693    if (!GlobalContext.instance) {
694      GlobalContext.instance = new GlobalContext();
695    }
696    return GlobalContext.instance;
697  }
698
699  getObject(value: string): Object | undefined {
700    return this._objects.get(value);
701  }
702
703  setObject(key: string, objectClass: Object): void {
704    this._objects.set(key, objectClass);
705  }
706}
707
708class EntryAbility extends UIAbility {
709  value:number = 0;
710  onWindowStageCreate(windowStage:window.WindowStage): void{
711    GlobalContext.getContext().setObject("value", this.value);
712  }
713}
714let context = GlobalContext.getContext().getObject("value");
715let serviceType = "_print._tcp";
716let discoveryService = mdns.createDiscoveryService(context as Context, serviceType);
717discoveryService.stopSearchingMDNS();
718```
719
720### on('discoveryStart')<sup>10+</sup>
721
722on(type: 'discoveryStart', callback: Callback<{serviceInfo: LocalServiceInfo, errorCode?: MdnsError}>): void
723
724Enables listening for **discoveryStart** events.
725
726**System capability**: SystemCapability.Communication.NetManager.MDNS
727
728**Parameters**
729
730| Name       | Type                            | Mandatory| Description                                    |
731|-------------|--------------|-----------|-----------------------------------------------------|
732| type     | string                          | Yes      |Event type. This field has a fixed value of **discoveryStart**.<br>**discoveryStart**: event of starting discovery of mDNS services on the LAN.|
733| callback | Callback<{serviceInfo: [LocalServiceInfo](#localserviceinfo), errorCode?: [MdnsError](#mdnserror)}>                  | Yes       |   Callback used to return the mDNS service and error information.     |
734
735**Example**
736
737```ts
738import mdns from '@ohos.net.mdns'
739import UIAbility from '@ohos.app.ability.UIAbility';
740import { BusinessError } from '@ohos.base';
741import window from '@ohos.window';
742
743export class GlobalContext {
744  private constructor() {}
745  private static instance: GlobalContext;
746  private _objects = new Map<string, Object>();
747
748  public static getContext(): GlobalContext {
749    if (!GlobalContext.instance) {
750      GlobalContext.instance = new GlobalContext();
751    }
752    return GlobalContext.instance;
753  }
754
755  getObject(value: string): Object | undefined {
756    return this._objects.get(value);
757  }
758
759  setObject(key: string, objectClass: Object): void {
760    this._objects.set(key, objectClass);
761  }
762}
763
764class EntryAbility extends UIAbility {
765  value:number = 0;
766  onWindowStageCreate(windowStage:window.WindowStage): void{
767    GlobalContext.getContext().setObject("value", this.value);
768  }
769}
770
771// See mdns.createDiscoveryService.
772class DataServiceInfo{
773  serviceInfo: mdns.LocalServiceInfo|null = null
774  errorCode?: mdns.MdnsError = 0
775}
776let context = GlobalContext.getContext().getObject("value");
777let serviceType = "_print._tcp";
778let discoveryService = mdns.createDiscoveryService(context as Context, serviceType);
779discoveryService.startSearchingMDNS();
780
781discoveryService.on('discoveryStart', (data: DataServiceInfo) => {
782  console.log(JSON.stringify(data));
783});
784
785discoveryService.stopSearchingMDNS();
786```
787
788### off('discoveryStart')<sup>10+</sup>
789
790off(type: 'discoveryStart', callback?: Callback<{ serviceInfo: LocalServiceInfo, errorCode?: MdnsError }>): void
791
792Disables listening for **discoveryStart** events.
793
794**System capability**: SystemCapability.Communication.NetManager.MDNS
795
796**Parameters**
797
798| Name       | Type                            | Mandatory| Description                                    |
799|-------------|--------------|-----------|-----------------------------------------------------|
800| type     | string                          | Yes      |Event type. This field has a fixed value of **discoveryStart**.<br>**discoveryStart**: event of starting discovery of mDNS services on the LAN.|
801| callback | Callback<{serviceInfo: [LocalServiceInfo](#localserviceinfo), errorCode?: [MdnsError](#mdnserror)}>                  | No       |   Callback used to return the mDNS service and error information.     |
802
803**Example**
804
805```ts
806import mdns from '@ohos.net.mdns'
807import UIAbility from '@ohos.app.ability.UIAbility';
808import { BusinessError } from '@ohos.base';
809import window from '@ohos.window';
810
811export class GlobalContext {
812  private constructor() {}
813  private static instance: GlobalContext;
814  private _objects = new Map<string, Object>();
815
816  public static getContext(): GlobalContext {
817    if (!GlobalContext.instance) {
818      GlobalContext.instance = new GlobalContext();
819    }
820    return GlobalContext.instance;
821  }
822
823  getObject(value: string): Object | undefined {
824    return this._objects.get(value);
825  }
826
827  setObject(key: string, objectClass: Object): void {
828    this._objects.set(key, objectClass);
829  }
830}
831
832class EntryAbility extends UIAbility {
833  value:number = 0;
834  onWindowStageCreate(windowStage:window.WindowStage): void{
835    GlobalContext.getContext().setObject("value", this.value);
836  }
837}
838// See mdns.createDiscoveryService.
839let context = GlobalContext.getContext().getObject("value");
840let serviceType = "_print._tcp";
841let discoveryService = mdns.createDiscoveryService(context as Context, serviceType);
842discoveryService.startSearchingMDNS();
843
844interface Data {
845  serviceInfo: mdns.LocalServiceInfo,
846  errorCode?: mdns.MdnsError
847}
848discoveryService.on('discoveryStart', (data: Data) => {
849  console.log(JSON.stringify(data));
850});
851
852discoveryService.stopSearchingMDNS();
853
854discoveryService.off('discoveryStart', (data: Data) => {
855  console.log(JSON.stringify(data));
856});
857```
858
859### on('discoveryStop')<sup>10+</sup>
860
861on(type: 'discoveryStop', callback: Callback<{serviceInfo: LocalServiceInfo, errorCode?: MdnsError}>): void
862
863Enables listening for **discoveryStop** events.
864
865**System capability**: SystemCapability.Communication.NetManager.MDNS
866
867**Parameters**
868
869| Name       | Type                            | Mandatory| Description                                    |
870|-------------|--------------|-----------|-----------------------------------------------------|
871| type     | string                          | Yes      |Event type. This field has a fixed value of **discoveryStop**.<br>**discoveryStop**: event of stopping discovery of mDNS services on the LAN.|
872| callback | Callback<{serviceInfo: [LocalServiceInfo](#localserviceinfo), errorCode?: [MdnsError](#mdnserror)}>                 | Yes       |   Callback used to return the mDNS service and error information.     |
873
874**Example**
875
876```ts
877import mdns from '@ohos.net.mdns'
878import UIAbility from '@ohos.app.ability.UIAbility';
879import { BusinessError } from '@ohos.base';
880import window from '@ohos.window';
881
882export class GlobalContext {
883  private constructor() {}
884  private static instance: GlobalContext;
885  private _objects = new Map<string, Object>();
886
887  public static getContext(): GlobalContext {
888    if (!GlobalContext.instance) {
889      GlobalContext.instance = new GlobalContext();
890    }
891    return GlobalContext.instance;
892  }
893
894  getObject(value: string): Object | undefined {
895    return this._objects.get(value);
896  }
897
898  setObject(key: string, objectClass: Object): void {
899    this._objects.set(key, objectClass);
900  }
901}
902
903class EntryAbility extends UIAbility {
904  value:number = 0;
905  onWindowStageCreate(windowStage:window.WindowStage): void{
906    GlobalContext.getContext().setObject("value", this.value);
907  }
908}
909// See mdns.createDiscoveryService.
910let context = GlobalContext.getContext().getObject("value");
911let serviceType = "_print._tcp";
912let discoveryService = mdns.createDiscoveryService(context as Context, serviceType);
913discoveryService.startSearchingMDNS();
914
915interface Data {
916  serviceInfo: mdns.LocalServiceInfo,
917  errorCode?: mdns.MdnsError
918}
919discoveryService.on('discoveryStop', (data: Data) => {
920  console.log(JSON.stringify(data));
921});
922
923discoveryService.stopSearchingMDNS();
924```
925
926### off('discoveryStop')<sup>10+</sup>
927
928off(type: 'discoveryStop', callback?: Callback<{ serviceInfo: LocalServiceInfo, errorCode?: MdnsError }>): void
929
930Disables listening for **discoveryStop** events.
931
932**System capability**: SystemCapability.Communication.NetManager.MDNS
933
934**Parameters**
935
936| Name       | Type                            | Mandatory| Description                                    |
937|-------------|--------------|-----------|-----------------------------------------------------|
938| type     | string                          | Yes      |Event type. This field has a fixed value of **discoveryStop**.<br>**discoveryStop**: event of stopping discovery of mDNS services on the LAN.|
939| callback | Callback<{serviceInfo: [LocalServiceInfo](#localserviceinfo), errorCode?: [MdnsError](#mdnserror)}>                 | No       |   Callback used to return the mDNS service and error information.     |
940
941**Example**
942
943```ts
944import mdns from '@ohos.net.mdns'
945import UIAbility from '@ohos.app.ability.UIAbility';
946import { BusinessError } from '@ohos.base';
947import window from '@ohos.window';
948
949export class GlobalContext {
950  private constructor() {}
951  private static instance: GlobalContext;
952  private _objects = new Map<string, Object>();
953
954  public static getContext(): GlobalContext {
955    if (!GlobalContext.instance) {
956      GlobalContext.instance = new GlobalContext();
957    }
958    return GlobalContext.instance;
959  }
960
961  getObject(value: string): Object | undefined {
962    return this._objects.get(value);
963  }
964
965  setObject(key: string, objectClass: Object): void {
966    this._objects.set(key, objectClass);
967  }
968}
969
970class EntryAbility extends UIAbility {
971  value:number = 0;
972  onWindowStageCreate(windowStage:window.WindowStage): void{
973    GlobalContext.getContext().setObject("value", this.value);
974  }
975}
976// See mdns.createDiscoveryService.
977let context = GlobalContext.getContext().getObject("value");
978let serviceType = "_print._tcp";
979let discoveryService = mdns.createDiscoveryService(context as Context, serviceType);
980discoveryService.startSearchingMDNS();
981
982interface Data {
983  serviceInfo: mdns.LocalServiceInfo,
984  errorCode?: mdns.MdnsError
985}
986discoveryService.on('discoveryStop', (data: Data) => {
987  console.log(JSON.stringify(data));
988});
989
990discoveryService.stopSearchingMDNS();
991
992discoveryService.off('discoveryStop', (data: Data) => {
993  console.log(JSON.stringify(data));
994});
995```
996
997### on('serviceFound')<sup>10+</sup>
998
999on(type: 'serviceFound', callback: Callback\<LocalServiceInfo>): void
1000
1001Enables listening for **serviceFound** events.
1002
1003**System capability**: SystemCapability.Communication.NetManager.MDNS
1004
1005**Parameters**
1006
1007| Name       | Type                            | Mandatory| Description                                    |
1008|-------------|--------------|-----------|-----------------------------------------------------|
1009| type     | string                          | Yes      |Event type. This field has a fixed value of **serviceFound**.<br>**serviceFound**: event indicating an mDNS service is found.|
1010| callback | Callback<[LocalServiceInfo](#localserviceinfo)>                 | Yes       |   mDNS service information.     |
1011
1012**Example**
1013
1014```ts
1015import mdns from '@ohos.net.mdns'
1016import UIAbility from '@ohos.app.ability.UIAbility';
1017import { BusinessError } from '@ohos.base';
1018import window from '@ohos.window';
1019
1020export class GlobalContext {
1021  private constructor() {}
1022  private static instance: GlobalContext;
1023  private _objects = new Map<string, Object>();
1024
1025  public static getContext(): GlobalContext {
1026    if (!GlobalContext.instance) {
1027      GlobalContext.instance = new GlobalContext();
1028    }
1029    return GlobalContext.instance;
1030  }
1031
1032  getObject(value: string): Object | undefined {
1033    return this._objects.get(value);
1034  }
1035
1036  setObject(key: string, objectClass: Object): void {
1037    this._objects.set(key, objectClass);
1038  }
1039}
1040
1041class EntryAbility extends UIAbility {
1042  value:number = 0;
1043  onWindowStageCreate(windowStage:window.WindowStage): void{
1044    GlobalContext.getContext().setObject("value", this.value);
1045  }
1046}
1047// See mdns.createDiscoveryService.
1048let context = GlobalContext.getContext().getObject("value");
1049let serviceType = "_print._tcp";
1050let discoveryService = mdns.createDiscoveryService(context as Context, serviceType);
1051discoveryService.startSearchingMDNS();
1052
1053discoveryService.on('serviceFound', (data: mdns.LocalServiceInfo) => {
1054  console.log(JSON.stringify(data));
1055});
1056
1057discoveryService.stopSearchingMDNS();
1058```
1059
1060### off('serviceFound')<sup>10+</sup>
1061
1062off(type: 'serviceFound', callback?: Callback\<LocalServiceInfo>): void
1063
1064Disables listening for **serviceFound** events.
1065
1066**System capability**: SystemCapability.Communication.NetManager.MDNS
1067
1068**Parameters**
1069
1070| Name       | Type                            | Mandatory| Description                                    |
1071|-------------|--------------|-----------|-----------------------------------------------------|
1072| type     | string                          | Yes      |Event type. This field has a fixed value of **serviceFound**.<br>**serviceFound**: event indicating an mDNS service is found.|
1073| callback | Callback<[LocalServiceInfo](#localserviceinfo)>                 | No       |   mDNS service information.     |
1074
1075**Example**
1076
1077```ts
1078import mdns from '@ohos.net.mdns'
1079import UIAbility from '@ohos.app.ability.UIAbility';
1080import { BusinessError } from '@ohos.base';
1081import window from '@ohos.window';
1082
1083export class GlobalContext {
1084  private constructor() {}
1085  private static instance: GlobalContext;
1086  private _objects = new Map<string, Object>();
1087
1088  public static getContext(): GlobalContext {
1089    if (!GlobalContext.instance) {
1090      GlobalContext.instance = new GlobalContext();
1091    }
1092    return GlobalContext.instance;
1093  }
1094
1095  getObject(value: string): Object | undefined {
1096    return this._objects.get(value);
1097  }
1098
1099  setObject(key: string, objectClass: Object): void {
1100    this._objects.set(key, objectClass);
1101  }
1102}
1103
1104class EntryAbility extends UIAbility {
1105  value:number = 0;
1106  onWindowStageCreate(windowStage:window.WindowStage): void{
1107    GlobalContext.getContext().setObject("value", this.value);
1108  }
1109}
1110// See mdns.createDiscoveryService.
1111let context = GlobalContext.getContext().getObject("value");
1112let serviceType = "_print._tcp";
1113let discoveryService = mdns.createDiscoveryService(context as Context, serviceType);
1114discoveryService.startSearchingMDNS();
1115
1116discoveryService.on('serviceFound', (data: mdns.LocalServiceInfo) => {
1117  console.log(JSON.stringify(data));
1118});
1119
1120discoveryService.stopSearchingMDNS();
1121
1122discoveryService.off('serviceFound', (data: mdns.LocalServiceInfo) => {
1123  console.log(JSON.stringify(data));
1124});
1125```
1126
1127### on('serviceLost')<sup>10+</sup>
1128
1129on(type: 'serviceLost', callback: Callback\<LocalServiceInfo>): void
1130
1131Enables listening for **serviceLost** events.
1132
1133**System capability**: SystemCapability.Communication.NetManager.MDNS
1134
1135**Parameters**
1136
1137| Name       | Type                            | Mandatory| Description                                    |
1138|-------------|--------------|-----------|-----------------------------------------------------|
1139| type     | string                          | Yes      |Event type. This field has a fixed value of **serviceLost**.<br>serviceLost: event indicating that an mDNS service is removed.|
1140| callback | Callback<[LocalServiceInfo](#localserviceinfo)>   | Yes       |   mDNS service information.     |
1141
1142**Example**
1143
1144```ts
1145import mdns from '@ohos.net.mdns'
1146import UIAbility from '@ohos.app.ability.UIAbility';
1147import { BusinessError } from '@ohos.base';
1148import window from '@ohos.window';
1149
1150export class GlobalContext {
1151  private constructor() {}
1152  private static instance: GlobalContext;
1153  private _objects = new Map<string, Object>();
1154
1155  public static getContext(): GlobalContext {
1156    if (!GlobalContext.instance) {
1157      GlobalContext.instance = new GlobalContext();
1158    }
1159    return GlobalContext.instance;
1160  }
1161
1162  getObject(value: string): Object | undefined {
1163    return this._objects.get(value);
1164  }
1165
1166  setObject(key: string, objectClass: Object): void {
1167    this._objects.set(key, objectClass);
1168  }
1169}
1170
1171class EntryAbility extends UIAbility {
1172  value:number = 0;
1173  onWindowStageCreate(windowStage:window.WindowStage): void{
1174    GlobalContext.getContext().setObject("value", this.value);
1175  }
1176}
1177// See mdns.createDiscoveryService.
1178let context = GlobalContext.getContext().getObject("value");
1179let serviceType = "_print._tcp";
1180let discoveryService = mdns.createDiscoveryService(context as Context, serviceType);
1181discoveryService.startSearchingMDNS();
1182
1183discoveryService.on('serviceLost', (data: mdns.LocalServiceInfo) => {
1184  console.log(JSON.stringify(data));
1185});
1186
1187discoveryService.stopSearchingMDNS();
1188```
1189
1190### off('serviceLost')<sup>10+</sup>
1191
1192off(type: 'serviceLost', callback?: Callback\<LocalServiceInfo>): void
1193
1194Disables listening for **serviceLost** events.
1195
1196**System capability**: SystemCapability.Communication.NetManager.MDNS
1197
1198**Parameters**
1199
1200| Name       | Type                            | Mandatory| Description                                    |
1201|-------------|--------------|-----------|-----------------------------------------------------|
1202| type     | string                          | Yes      |Event type. This field has a fixed value of **serviceLost**.<br>serviceLost: event indicating that an mDNS service is removed.|
1203| callback | Callback<[LocalServiceInfo](#localserviceinfo)>   | No       |   mDNS service information.     |
1204
1205**Example**
1206
1207```ts
1208import mdns from '@ohos.net.mdns'
1209import UIAbility from '@ohos.app.ability.UIAbility';
1210import { BusinessError } from '@ohos.base';
1211import window from '@ohos.window';
1212
1213export class GlobalContext {
1214  private constructor() {}
1215  private static instance: GlobalContext;
1216  private _objects = new Map<string, Object>();
1217
1218  public static getContext(): GlobalContext {
1219    if (!GlobalContext.instance) {
1220      GlobalContext.instance = new GlobalContext();
1221    }
1222    return GlobalContext.instance;
1223  }
1224
1225  getObject(value: string): Object | undefined {
1226    return this._objects.get(value);
1227  }
1228
1229  setObject(key: string, objectClass: Object): void {
1230    this._objects.set(key, objectClass);
1231  }
1232}
1233
1234class EntryAbility extends UIAbility {
1235  value:number = 0;
1236  onWindowStageCreate(windowStage:window.WindowStage): void{
1237    GlobalContext.getContext().setObject("value", this.value);
1238  }
1239}
1240// See mdns.createDiscoveryService.
1241let context = GlobalContext.getContext().getObject("value");
1242let serviceType = "_print._tcp";
1243let discoveryService = mdns.createDiscoveryService(context as Context, serviceType);
1244discoveryService.startSearchingMDNS();
1245
1246discoveryService.on('serviceLost', (data: mdns.LocalServiceInfo) => {
1247  console.log(JSON.stringify(data));
1248});
1249
1250discoveryService.stopSearchingMDNS();
1251
1252discoveryService.off('serviceLost', (data: mdns.LocalServiceInfo) => {
1253  console.log(JSON.stringify(data));
1254});
1255```
1256
1257## LocalServiceInfo<sup>10+</sup>
1258
1259Defines the mDNS service information.
1260
1261**System capability**: SystemCapability.Communication.NetManager.MDNS
1262
1263| Name                 | Type                               | Mandatory| Description                    |
1264| --------------------- | ---------------------------------- | --- | ------------------------ |
1265| serviceType   | string                             |  Yes|  Type of the mDNS service. The value is in the format of **\_\<name>.<_tcp/_udp>**, where **name** contains a maximum of 63 characters excluding periods (.). |
1266| serviceName | string                             |  Yes|  Name of the mDNS service.  |
1267| port            | number           |  No|  Port number of the mDNS server.          |
1268| host           |  [NetAddress](js-apis-net-connection.md#netaddress) |  No|  IP address of the device that provides the mDNS service. The IP address is not effective when an mDNS service is added or removed.              |
1269| serviceAttribute     | serviceAttribute\<[ServiceAttribute](#serviceattribute)> |  No|  mDNS service attribute information.              |
1270
1271## ServiceAttribute<sup>10+</sup>
1272
1273Defines the mDNS service attribute information.
1274
1275**System capability**: SystemCapability.Communication.NetManager.MDNS
1276
1277| Name                 | Type                               | Mandatory| Description                    |
1278| --------------------- | ---------------------------------- | --- | ------------------------ |
1279| key   | string                             |  Yes|  mDNS service attribute key. The value contains a maximum of 9 characters. |
1280| value | Array\<number>                             |  Yes|  mDNS service attribute value.  |
1281
1282## MdnsError
1283
1284Defines the mDNS error information.
1285
1286**System capability**: SystemCapability.Communication.NetManager.MDNS
1287
1288| Name        | Value  | Description       |
1289| --------------- | ---- | ----------- |
1290| INTERNAL_ERROR  | 0    | Operation failed because of an internal error. (not supported currently) |
1291| ALREADY_ACTIVE      | 1    | Operation failed because the service already exists. (not supported currently)|
1292| MAX_LIMIT  | 2 | Operation failed because the number of requests exceeds the maximum value. (not supported currently)|
1293