Pal Szasz
Pal Szasz

Reputation: 3225

How to change android device name used by NsdManager?

I am using NsdManager to register a web service on the local network. My problem is that the device name is called "android", so I can access the phone as "android.local" from my laptop. How can I change that name? I would like something more unique.

Upvotes: 5

Views: 1412

Answers (2)

JanH
JanH

Reputation: 21

While you cannot modify the default name without root, you can advertise additional mDNS names by e.g. adding JmDNS as a dependency and configuring it accordingly:

package org.example.util;

import android.util.Log;

import androidx.annotation.Nullable;

import java.io.IOException;
import java.net.InetAddress;
import java.util.Objects;

import javax.jmdns.JmDNS;

/**
 * Advertises a custom .local hostname via mDNS
 */
public class HostnameBroadcaster {
    private static final String LOGTAG = "mDNS";

    private static JmDNS sJmDNS;
    private static String sHostname;

    private HostnameBroadcaster() {}

    /**
     * Set the hostname to be advertised via mDNS.
     * <p>
     * Note: JmDNS does some network accesses on the calling thread on startup, so don't call this
     * method on the UI thread.
     *
     * @param addr The IP address to bind to. If <code>null</code>, JmDNS's auto-binding will be
     *             used.
     * @param hostname The hostname to advertise via mDNS. If <code>null</code>, the broadcaster is
     *                 shut down.
     */
    public static void setHostname(@Nullable InetAddress addr, @Nullable String hostname) {
        if (Objects.equals(sHostname, hostname)) {
            return;
        }

        if (sJmDNS != null) {
            try {
                sJmDNS.close();
            } catch (IOException e) {
                Log.d(LOGTAG, "Error stopping mDNS hostname broadcaster", e);
            }
            sJmDNS = null;
        }

        if (hostname != null) {
            try {
                sJmDNS = JmDNS.create(addr, hostname);
            } catch (IOException e) {
                Log.d(LOGTAG, "Error starting mDNS hostname broadcaster", e);
            }
        }

        sHostname = hostname;
    }
}

Upvotes: 0

artkoenig
artkoenig

Reputation: 7257

You cannot change this (on non-rooted devices). "android" is the host name of the device, ".local" is the suffix added by the mDNS (see this article).

Upvotes: 0

Related Questions