Skip to content

Kotlin multiplatform implemention of DNS Service Discovery

License

Notifications You must be signed in to change notification settings

Appstractive/dns-sd-kt

Repository files navigation

DNS-SD Kotlin Multiplatform

Maven Central

badge badge badge badge badge

This library implements Multicast DNS and DNS-Based Service Discovery to provide zero-configuration operations for Kotlin Multiplatform. It lets you announce and find services in a .local domain.

The platform implementations are based on:

Usage

Installation

Gradle:

implementation("com.appstractive:dns-sd-kt:1.0.1")

Permissions

Android

Add the following permissions to your manifest:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />

Apple

Add the following permissions to your Info.plist (replace service type with your own):

<key>NSLocalNetworkUsageDescription</key>
<string>Required to discover local network devices</string>
<key>NSBonjourServices</key>
<array>
<string>_http._tcp</string>
</array>

Publish a service

Manually:

val service = createNetService(
  type = "_myservice._tcp",
  name = "MyService",
) {
  port = 8080
  addresses = null // platforms default addresses
  txt =
      mapOf(
          "key1" to "value1",
          "key2" to "value2",
      )
}

// start publication to network
service.register()

if(service.registered) {
    // stop publication to network
    service.unregister()
}

Scope based:

val scope = CoroutineScope(Dispatchers.Main) // or lifecycleScope/viewModelScope

scope.launch {
  publishService(
      type = "_myservice._tcp",
      name = "MyService",
  ) {
    port = 8080
    addresses = null // platforms default addresses
    txt =
        mapOf(
            "key1" to "value1",
            "key2" to "value2",
        )
  }
}

// when the scope is cancelled, the service automatically unregisters itself
scope.cancel()

Discover services

val services: Map<String, DiscoveredService> = mutableMapOf()

discoverServices("_myservice._tcp").collect {
    when (it) {
        is DiscoveryEvent.Discovered -> {
          scannedServices[it.service.key] = it.service
          // optionally resolve ip addresses of the service
          it.resolve()
        }
        is DiscoveryEvent.Removed -> {
          scannedServices.remove(it.service.key)
        }
        is DiscoveryEvent.Resolved -> {
          scannedServices[it.service.key] = it.service
        }
    }
}

Sample App

This repository contains a sample compose multiplatform application to demonstrate the usage on the platforms Android, iOS and Desktop JVM.

Android iOS Desktop JVM
Android Screenshot iOS Screenshot Desktop JVM Screenshot

Run

Android

./gradlew installDebug

iOS

Open sample/iosApp/iosApp.xcworkspace in XCode build and run

JVM

./gradlew ":sample:composeApp:run"