2

I am using the NSD (Network Service Discovery) NsdManager.DiscoveryListener to discover services on the network. However, in the onServiceFound method, I am sometimes unable to retrieve the IP address from the NsdServiceInfo object. Despite consulting the official documentation and adhering to best practices, However, I am still encountering situations where the IP address cannot be retrieved, even though the MAC address is available. I am testing this on my Pixel 6 device running Android version 13.

I have referred to the following link: https://developer.android.com/training/connect-devices-wirelessly/nsd#discover.

Code:

private val discoveryListener = object : NsdManager.DiscoveryListener {

    override fun onDiscoveryStarted(regType: String) {
        Log.d(TAG, "Service discovery started")
    }

    override fun onServiceFound(service: NsdServiceInfo) {
        Log.d(TAG, "Service discovery success$service")
        // However, I am still encountering situations where the IP address cannot be retrieved, even though the MAC address is available.
    }

    override fun onServiceLost(service: NsdServiceInfo) {
        Log.e(TAG, "service lost: $service")
    }

    override fun onDiscoveryStopped(serviceType: String) {
        Log.i(TAG, "Discovery stopped: $serviceType")
    }

    override fun onStartDiscoveryFailed(serviceType: String, errorCode: Int) {
        nsdManager.stopServiceDiscovery(this)
    }

    override fun onStopDiscoveryFailed(serviceType: String, errorCode: Int) {
        nsdManager.stopServiceDiscovery(this)
    }
}

And for connection code:

private val resolveListener = object : NsdManager.ResolveListener {

    override fun onResolveFailed(serviceInfo: NsdServiceInfo, errorCode: Int) {
        // Called when the resolve fails. Use the error code to debug.
        Log.e(TAG, "Resolve failed: $errorCode")
    }

    override fun onServiceResolved(serviceInfo: NsdServiceInfo) {
        Log.e(TAG, "Resolve Succeeded. $serviceInfo")

        if (serviceInfo.serviceName == mServiceName) {
            Log.d(TAG, "Same IP.")
            return
        }
        mService = serviceInfo
        val port: Int = serviceInfo.port
        val host: InetAddress = serviceInfo.host
    }
}
Pratik A
  • 31
  • 3

0 Answers0