I am trying to find the hostname from the IP addresses in the subnet ( reverse DNS ) from my android app. I have not been able to find an approach which works on a decent number of routers.
Approaches tried so far
getCanonicalHostName
Works well with some routers. Does not work in the rest and just returns the IP.
DNSJava library.
I tried the below code which also works with some cases and not in other routers.
String getHostNameUsingDNSJavaLibrary( String ipAddress ) { try { Name reverseipAddress = ReverseMap.fromAddress( ipAddress ); Log.e( TAG ,"reverseipAddress="+ reverseipAddress ); Record[] records; Lookup lookup = new Lookup( reverseipAddress, Type.PTR ); SimpleResolver resolver = new SimpleResolver(); resolver.setAddress( InetAddress.getByName( ModemIPAddress ) ); lookup.setResolver( resolver ); records = lookup.run(); if ( lookup.getResult() == Lookup.SUCCESSFUL ) { for (int i = 0; i < records.length; i++) { if( records[i] instanceof PTRRecord ) { PTRRecord ptr = (PTRRecord) records[i]; return records[0].rdataToString(); } } } else { Log.e( TAG ,"Failed lookup"+ lookup.getResult() ); } } catch(Exception e) { Log.e( TAG ,"Exception: " + e); } return ipAddress;
}
Linux commands
I have tried running commands like nslookup, host, dig on the android linux terminal but the commands don't work. Eg: OnePlus5T:/ $ dig -x
/system/bin/sh: dig: inaccessible or not found
Apps like fing do this better. Even fing cannot find all the hostnames of devices in the network but its much better than what I have been able to accomplish. There are similar questions like this Can't do reverse DNS lookup on Android but there hasn't been convincing answers.
Any help to make it better is appreciated.