Tanmay Ranjan
Tanmay Ranjan

Reputation: 324

How to resolve Ipv4 and Ipv6 from ".local" using mDNS in Android

I am trying to resolve IPv4 and IpV6 from ".local" using multicast DNS and I tried https://github.com/posicks/mdnsjava but it unable to resolve required ipv4/ipv6. Alternatively, I found one app which work for me but have no idea how it works.

App Link : https://play.google.com/store/apps/details?id=com.dokoden.dotlocalfinder

Also I am trying to resolve ".local" using Linux Terminal -
Command used to resolve ipv4 avahi-resolve-host-name abc.local -4
Command used to resolve ipv6 avahi-resolve-host-name abc.local -6
and it resolved successfully.

I am tried same command in Android to resolve ".local" but getting Cannot run program "avahi-resolve-host-name": error=13, Permission denied

I am trying this piece of code in Android -

  Process process = Runtime.getRuntime().exec("avahi-resolve-host-name abc.local -4");
  BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
  Log.d("OutPut",in.readLine());

Upvotes: 5

Views: 3408

Answers (2)

Tanmay Ranjan
Tanmay Ranjan

Reputation: 324

Finally, I got success.

I resolved Ipv4 and Ipv6 using mdnsjava dependency i.e.

implementation "xyz.gianlu.mdnsjava:mdnsjava:2.2.1"

For resolving Ipv4 I use this code snippet

for (Record record : new Lookup(localName, Type.A, DClass.IN).lookupRecords()) {
   if (record.getType() == Type.A) {
       ((ARecord) record).getAddress().getHostAddress();
       }
    }

Before writing this code snippet you have to put MuticastLock on connected Wifi using

  WifiManager.MulticastLock multicastLoc = wifiManager.createMulticastLock("mDnsLock");
  multicastLoc.setReferenceCounted(true);
  multicastLoc.acquire();

and after getting ip release multicastLock.

For Ipv6 I used same Ipv4 code snippet only here the record type should be Type.AAAA in place of Type.A

This code works up to Android 10.

Upvotes: 2

niek tuytel
niek tuytel

Reputation: 1179

I am not 100% this will work, but as comment is was to large.

  1. check the following permissions in your AndroidManifest.xml
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
  1. Following links might be usefull:

Upvotes: 1

Related Questions