openharmony 鸿蒙 js-apis-net-mdns

2025-06-12 浏览 (1)

@ohos.net.mdns (MDNS Management)

Multicast DNS (MDNS) provides functions such as adding, removing, discovering, and resolving local services on a LAN.

NOTE 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.

Modules to Import

import { mdns } from '@kit.NetworkKit';

mdns.addLocalService

addLocalService(context: Context, serviceInfo: LocalServiceInfo, callback: AsyncCallback<LocalServiceInfo>): void

Adds an MDNS service. This API uses an asynchronous callback to return the result.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.Communication.NetManager.MDNS

Parameters

NameTypeMandatoryDescription
contextContextYesApplication context.
For details about the application context of the FA model, see Context.
For the application context of the stage model, see Context.
serviceInfoLocalServiceInfoYesMDNS service information.
callbackAsyncCallback<LocalServiceInfo>YesCallback used to return the result. If the operation is successful, error is undefined and data is the MDNS service information.

Error codes

IDError Message
401Parameter error.
2100002Failed to connect to the service.
2100003System internal error.
2204003Callback duplicated.
2204008Failed to delete the service instance.
2204010Failed to send the message.

NOTE For details about the error codes, see MDNS Error Codes.

Example

Stage model:

import { mdns } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';

// Obtain the context.
let context = getContext(this) as Context;

let localServiceInfo: mdns.LocalServiceInfo = {
  serviceType: "_print._tcp",
  serviceName: "servicename",
  port: 5555,
  host: {
  address: "10.14.**.***",
  },
  serviceAttribute: [{key: "111", value: [1]}]
}

mdns.addLocalService(context, localServiceInfo, (error:BusinessError, data:mdns.LocalServiceInfo) =>  {
  console.log(JSON.stringify(error));
  console.log(JSON.stringify(data));
});

mdns.addLocalService

addLocalService(context: Context, serviceInfo: LocalServiceInfo): Promise<LocalServiceInfo>

Adds an MDNS service. This API uses a promise to return the result.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.Communication.NetManager.MDNS

Parameters

NameTypeMandatoryDescription
contextContextYesApplication context.
For details about the application context of the FA model, see Context.
For the application context of the stage model, see Context.
serviceInfoLocalServiceInfoYesMDNS service information.

Return value

TypeDescription
Promise<LocalServiceInfo>Promise used to return the result.

Error codes

IDError Message
401Parameter error.
2100002Failed to connect to the service.
2100003System internal error.
2204003Callback duplicated.
2204008Failed to delete the service instance.
2204010Failed to send the message.

NOTE For details about the error codes, see MDNS Error Codes.

Example

Stage model:

import { mdns } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';

// Obtain the context.
let context = getContext(this) as Context;

let localServiceInfo: mdns.LocalServiceInfo = {
  serviceType: "_print._tcp",
  serviceName: "servicename",
  port: 5555,
  host: {
    address: "10.14.**.***",
  },
  serviceAttribute: [{key: "111", value: [1]}]
}

mdns.addLocalService(context, localServiceInfo).then((data: mdns.LocalServiceInfo) => {
  console.log(JSON.stringify(data));
});

mdns.removeLocalService

removeLocalService(context: Context, serviceInfo: LocalServiceInfo, callback: AsyncCallback<LocalServiceInfo>): void

Removes an MDNS service. This API uses an asynchronous callback to return the result.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.Communication.NetManager.MDNS

Parameters

NameTypeMandatoryDescription
contextContextYesApplication context.
For details about the application context of the FA model, see Context.
For the application context of the stage model, see Context.
serviceInfoLocalServiceInfoYesMDNS service information.
callbackAsyncCallback<LocalServiceInfo>YesCallback used to return the result. If the operation is successful, error is undefined and data is the MDNS service information.

Error codes

IDError Message
401Parameter error.
2100002Failed to connect to the service.
2100003System internal error.
2204002Callback not found.
2204008Failed to delete the service instance.
2204010Failed to send the message.

NOTE For details about the error codes, see MDNS Error Codes.

Example

Stage model:

import { mdns } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';

// Obtain the context.
let context = getContext(this) as Context;

let localServiceInfo: mdns.LocalServiceInfo = {
  serviceType: "_print._tcp",
  serviceName: "servicename",
  port: 5555,
  host: {
  address: "10.14.**.***",
  },
  serviceAttribute: [{key: "111", value: [1]}]
}

mdns.removeLocalService(context, localServiceInfo, (error: BusinessError, data: mdns.LocalServiceInfo) =>  {
  console.log(JSON.stringify(error));
  console.log(JSON.stringify(data));
});

mdns.removeLocalService

removeLocalService(context: Context, serviceInfo: LocalServiceInfo): Promise<LocalServiceInfo>

Removes an MDNS service. This API uses a promise to return the result.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.Communication.NetManager.MDNS

Parameters

NameTypeMandatoryDescription
contextContextYesApplication context.
For details about the application context of the FA model, see Context.
For the application context of the stage model, see Context.
serviceInfoLocalServiceInfoYesMDNS service information.

Return value

TypeDescription
Promise<LocalServiceInfo>Promise used to return the result.

Error codes

IDError Message
401Parameter error.
2100002Failed to connect to the service.
2100003System internal error.
2204002Callback not found.
2204008Failed to delete the service instance.
2204010Failed to send the message.

NOTE For details about the error codes, see MDNS Error Codes.

Example

Stage model:

import { mdns } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';

let context = getContext(this) as Context;

let localServiceInfo: mdns.LocalServiceInfo = {
  serviceType: "_print._tcp",
  serviceName: "servicename",
  port: 5555,
  host: {
  address: "10.14.**.***",
  },
  serviceAttribute: [{key: "111", value: [1]}]
}

mdns.removeLocalService(context, localServiceInfo).then((data: mdns.LocalServiceInfo) => {
  console.log(JSON.stringify(data));
});

mdns.createDiscoveryService

createDiscoveryService(context: Context, serviceType: string): DiscoveryService

Creates a DiscoveryService object, which is used to discover MDNS services of the specified type.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.Communication.NetManager.MDNS

Parameters

NameTypeMandatoryDescription
contextContextYesApplication context.
For details about the application context of the FA model, see Context.
For the application context of the stage model, see Context.
serviceTypestringYesType of the MDNS services to be discovered.

Return value

TypeDescription
DiscoveryServiceDiscoveryService object used to discover MDNS services based on the specified serviceType and Context.

Error codes

IDError Message
401Parameter error.

Example

Stage model:

import { mdns } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';

// Obtain the context.
let context = getContext(this) as Context;

let serviceType = "_print._tcp";
let discoveryService : Object = mdns.createDiscoveryService(context, serviceType);

mdns.resolveLocalService

resolveLocalService(context: Context, serviceInfo: LocalServiceInfo, callback: AsyncCallback<LocalServiceInfo>): void

Resolves an MDNS service. This API uses an asynchronous callback to return the result.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.Communication.NetManager.MDNS

Parameters

NameTypeMandatoryDescription
contextContextYesApplication context.
For details about the application context of the FA model, see Context.
For the application context of the stage model, see Context.
serviceInfoLocalServiceInfoYesMDNS service information.
callbackAsyncCallback<LocalServiceInfo>YesCallback used to return the result. If the operation is successful, error is undefined and data is the MDNS service information.

Error codes

IDError Message
401Parameter error.
2100002Failed to connect to the service.
2100003System internal error.
2204003Callback duplicated.
2204006Request timeout.
2204010Failed to send the message.

NOTE For details about the error codes, see MDNS Error Codes.

Example

Stage model:

import { mdns } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';

// Obtain the context.
let context = getContext(this) as Context;

let localServiceInfo: mdns.LocalServiceInfo = {
  serviceType: "_print._tcp",
  serviceName: "servicename",
  port: 5555,
  host: {
  address: "10.14.**.***",
  },
  serviceAttribute: [{key: "111", value: [1]}]
}

mdns.resolveLocalService(context, localServiceInfo, (error: BusinessError, data: mdns.LocalServiceInfo) =>  {
  console.log(JSON.stringify(error));
  console.log(JSON.stringify(data));
});

mdns.resolveLocalService

resolveLocalService(context: Context, serviceInfo: LocalServiceInfo): Promise<LocalServiceInfo>

Resolves an MDNS service. This API uses a promise to return the result.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.Communication.NetManager.MDNS

Parameters

NameTypeMandatoryDescription
contextContextYesApplication context.
For details about the application context of the FA model, see Context.
For the application context of the stage model, see Context.
serviceInfoLocalServiceInfoYesMDNS service information.

Return value

TypeDescription
Promise<LocalServiceInfo>Promise used to return the result.

Error codes

IDError Message
401Parameter error.
2100002Failed to connect to the service.
2100003System internal error.
2204003Callback duplicated.
2204006Request timeout.
2204010Failed to send the message.

NOTE For details about the error codes, see MDNS Error Codes.

Example

Stage model:

import { mdns } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';

// Obtain the context.
let context = getContext(this) as Context;

let localServiceInfo: mdns.LocalServiceInfo = {
  serviceType: "_print._tcp",
  serviceName: "servicename",
  port: 5555,
  host: {
  address: "10.14.**.***",
  },
  serviceAttribute: [{key: "111", value: [1]}]
}

mdns.resolveLocalService(context, localServiceInfo).then((data: mdns.LocalServiceInfo) => {
  console.log(JSON.stringify(data));
});

DiscoveryService

Defines a DiscoveryService object for discovering MDNS services of the specified type.

startSearchingMDNS

startSearchingMDNS(): void

Searches for MDNS services on the LAN.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.Communication.NetManager.MDNS

Example

Stage model:

import { mdns } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';

// Obtain the context.
let context = getContext(this) as Context;
let serviceType = "_print._tcp";
let discoveryService = mdns.createDiscoveryService(context, serviceType);
discoveryService.startSearchingMDNS();

stopSearchingMDNS

stopSearchingMDNS(): void

Stops searching for MDNS services on the LAN.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.Communication.NetManager.MDNS

Example

Stage model:

import { mdns } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';

// Obtain the context.
let context = getContext(this) as Context;
let serviceType = "_print._tcp";
let discoveryService = mdns.createDiscoveryService(context, serviceType);
discoveryService.stopSearchingMDNS();

on('discoveryStart')

on(type: 'discoveryStart', callback: Callback<DiscoveryEventInfo>): void

Enables listening for discoveryStart events.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.Communication.NetManager.MDNS

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. This field has a fixed value of discoveryStart.
discoveryStart: event of starting discovery of MDNS services on the LAN.
callbackCallback<DiscoveryEventInfo>YesCallback used to return the MDNS service and error information.

Example

import { mdns } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';

// See mdns.createDiscoveryService.
let context = getContext(this) as Context;
let serviceType = "_print._tcp";
let discoveryService = mdns.createDiscoveryService(context, serviceType);
discoveryService.startSearchingMDNS();

discoveryService.on('discoveryStart', (data: mdns.DiscoveryEventInfo) => {
  console.log(JSON.stringify(data));
});

discoveryService.stopSearchingMDNS();

off('discoveryStart')

off(type: 'discoveryStart', callback?: Callback<DiscoveryEventInfo>): void

Disables listening for discoveryStart events.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.Communication.NetManager.MDNS

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. This field has a fixed value of discoveryStart.
discoveryStart: event of starting discovery of MDNS services on the LAN.
callbackCallback<DiscoveryEventInfo>NoCallback used to return the MDNS service and error information.

Example

import { mdns } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';

// See mdns.createDiscoveryService.
let context = getContext(this) as Context;
let serviceType = "_print._tcp";
let discoveryService = mdns.createDiscoveryService(context, serviceType);
discoveryService.startSearchingMDNS();

discoveryService.on('discoveryStart', (data: mdns.DiscoveryEventInfo) => {
  console.log(JSON.stringify(data));
});

discoveryService.stopSearchingMDNS();

discoveryService.off('discoveryStart', (data: mdns.DiscoveryEventInfo) => {
  console.log(JSON.stringify(data));
});

on('discoveryStop')

on(type: 'discoveryStop', callback: Callback<DiscoveryEventInfo>): void

Enables listening for discoveryStop events.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.Communication.NetManager.MDNS

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. This field has a fixed value of discoveryStop.
discoveryStop: event of stopping discovery of MDNS services on the LAN.
callbackCallback<DiscoveryEventInfo>YesCallback used to return the MDNS service and error information.

Example

import { mdns } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';

// See mdns.createDiscoveryService.
let context = getContext(this) as Context;
let serviceType = "_print._tcp";
let discoveryService = mdns.createDiscoveryService(context, serviceType);
discoveryService.startSearchingMDNS();

discoveryService.on('discoveryStop', (data: mdns.DiscoveryEventInfo) => {
  console.log(JSON.stringify(data));
});

discoveryService.stopSearchingMDNS();

off('discoveryStop')

off(type: 'discoveryStop', callback?: Callback<DiscoveryEventInfo>): void

Disables listening for discoveryStop events.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.Communication.NetManager.MDNS

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. This field has a fixed value of discoveryStop.
discoveryStop: event of stopping discovery of MDNS services on the LAN.
callbackCallback<DiscoveryEventInfo>NoCallback used to return the MDNS service and error information.

Example

import { mdns } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';

// See mdns.createDiscoveryService.
let context = getContext(this) as Context;
let serviceType = "_print._tcp";
let discoveryService = mdns.createDiscoveryService(context, serviceType);
discoveryService.startSearchingMDNS();

discoveryService.on('discoveryStop', (data: mdns.DiscoveryEventInfo) => {
  console.log(JSON.stringify(data));
});

discoveryService.stopSearchingMDNS();

discoveryService.off('discoveryStop', (data: mdns.DiscoveryEventInfo) => {
  console.log(JSON.stringify(data));
});

on('serviceFound')

on(type: 'serviceFound', callback: Callback<LocalServiceInfo>): void

Enables listening for serviceFound events.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.Communication.NetManager.MDNS

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. This field has a fixed value of serviceFound.
serviceFound: event indicating an MDNS service is found.
callbackCallback<LocalServiceInfo>YesCallback used to return the MDNS service information. You need to call resolveLocalService to parse the information.

Example

import { mdns } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';

// See mdns.createDiscoveryService.
let context = getContext(this) as Context;
let serviceType = "_print._tcp";
let discoveryService = mdns.createDiscoveryService(context, serviceType);
discoveryService.startSearchingMDNS();

discoveryService.on('serviceFound', (data: mdns.LocalServiceInfo) => {
  console.info('serviceFound', JSON.stringify(data));
  mdns.resolveLocalService(context, data, (error: BusinessError, resolveData: mdns.LocalServiceInfo) =>  {
    console.info('serviceFound', JSON.stringify(resolveData));
  });
});

discoveryService.stopSearchingMDNS();

off('serviceFound')

off(type: 'serviceFound', callback?: Callback<LocalServiceInfo>): void

Disables listening for serviceFound events.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.Communication.NetManager.MDNS

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. This field has a fixed value of serviceFound.
serviceFound: event indicating an MDNS service is found.
callbackCallback<LocalServiceInfo>NoMDNS service information.

Example

import { mdns } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';

// See mdns.createDiscoveryService.
let context = getContext(this) as Context;
let serviceType = "_print._tcp";
let discoveryService = mdns.createDiscoveryService(context, serviceType);
discoveryService.startSearchingMDNS();

discoveryService.on('serviceFound', (data: mdns.LocalServiceInfo) => {
  console.info('serviceFound', JSON.stringify(data));
  mdns.resolveLocalService(context, data, (error: BusinessError, resolveData: mdns.LocalServiceInfo) =>  {
    console.info('serviceFound', JSON.stringify(resolveData));
  });
});

discoveryService.stopSearchingMDNS();

discoveryService.off('serviceFound', (data: mdns.LocalServiceInfo) => {
  console.log(JSON.stringify(data));
});

on('serviceLost')

on(type: 'serviceLost', callback: Callback<LocalServiceInfo>): void

Enables listening for serviceLost events.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.Communication.NetManager.MDNS

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. This field has a fixed value of serviceLost.
serviceLost: event indicating that an MDNS service is removed.
callbackCallback<LocalServiceInfo>YesMDNS service information.

Example

import { mdns } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';

// See mdns.createDiscoveryService.
let context = getContext(this) as Context;
let serviceType = "_print._tcp";
let discoveryService = mdns.createDiscoveryService(context, serviceType);
discoveryService.startSearchingMDNS();

discoveryService.on('serviceLost', (data: mdns.LocalServiceInfo) => {
  console.log(JSON.stringify(data));
});

discoveryService.stopSearchingMDNS();

off('serviceLost')

off(type: 'serviceLost', callback?: Callback<LocalServiceInfo>): void

Disables listening for serviceLost events.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.Communication.NetManager.MDNS

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. This field has a fixed value of serviceLost.
serviceLost: event indicating that an MDNS service is removed.
callbackCallback<LocalServiceInfo>NoMDNS service information.

Example

import { mdns } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';

// See mdns.createDiscoveryService.
let context = getContext(this) as Context;
let serviceType = "_print._tcp";
let discoveryService = mdns.createDiscoveryService(context, serviceType);
discoveryService.startSearchingMDNS();

discoveryService.on('serviceLost', (data: mdns.LocalServiceInfo) => {
  console.log(JSON.stringify(data));
});

discoveryService.stopSearchingMDNS();

discoveryService.off('serviceLost', (data: mdns.LocalServiceInfo) => {
  console.log(JSON.stringify(data));
});

LocalServiceInfo

Defines the MDNS service information.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.Communication.NetManager.MDNS

NameTypeMandatoryDescription
serviceTypestringYesType of the MDNS service. The value is in the format of _<name>.<_tcp/_udp>, where name contains a maximum of 63 characters excluding periods (.).
serviceNamestringYesName of the MDNS service.
portnumberNoPort number of the MDNS server.
hostNetAddressNoIP address of the device that provides the MDNS service. The IP address is not effective when an MDNS service is added or removed.
serviceAttributeArray<ServiceAttribute>NoMDNS service attribute information.

ServiceAttribute

Defines the MDNS service attribute information.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.Communication.NetManager.MDNS

NameTypeMandatoryDescription
keystringYesMDNS service attribute key. The value contains a maximum of 9 characters.
valueArray<number>YesMDNS service attribute value.

DiscoveryEventInfo11+

Defines the MDNS service event information.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.Communication.NetManager.MDNS

NameTypeMandatoryDescription
serviceInfoLocalServiceInfoYesMDNS service information.
errorCodeMdnsErrorNoDefines the MDNS error information.

MdnsError

Defines the MDNS error information.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.Communication.NetManager.MDNS

NameValueDescription
INTERNAL_ERROR0Operation failed because of an internal error.
ALREADY_ACTIVE1Operation failed because the service already exists.
MAX_LIMIT2Operation failed because the number of requests exceeds the maximum value.

NetAddress

type NetAddress = connection.NetAddress

Obtains the network address.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Communication.NetManager

TypeDescription
connection.NetAddressNetwork address.

你可能感兴趣的鸿蒙文章

harmony 鸿蒙Network Kit

harmony 鸿蒙NetConn_ConnectionProperties

harmony 鸿蒙NetConn_HttpProxy

harmony 鸿蒙NetConn_NetAddr

harmony 鸿蒙NetConn_NetCapabilities

harmony 鸿蒙NetConn_NetConnCallback

harmony 鸿蒙NetConn_NetHandle

harmony 鸿蒙NetConn_NetHandleList

harmony 鸿蒙NetConn_NetSpecifier

harmony 鸿蒙NetConn_Route

  • 所属分类: 后端技术
  • 本文标签: 软件 鸿蒙
  • 版权声明: 本文链接 https://seaxiang.com/blog/MtuWl1