I am working on wifi based chat engine and I was able to retrieve the list of hosts connected to current wifi network by followin this link and now got list of devices with ip addresses but i need host name from the ip address and tried following
InetAddress inetAddr;
try {
inetAddr = InetAddress.getByName(host.hostname);
String hostname = inetAddr.getHostName();
String canonicalHostname = inetAddr.getCanonicalHostName();
holder.computerName.setText("Canonical : "+host.hostname);
} catch (Exception e) {
e.printStackTrace();
}
Here the host name and canonical host name both are displaying ip address rather than host name.
Please help me how to achieve this.
I think you might do that this way:
try {
Log.d("ReverseDNS", "Reverse DNS for 8.8.8.8 is: " + InetAddress.getByName("8.8.8.8").getHostName());
} catch (UnknownHostException e) {
Log.e("ReverseDNS", "Oh no, 8.8.8.8 has no reverse DNS record!");
}
A few additional things:
Take in consideration that this is an operation that might take a long time (understanding as a long time several seconds), so this is absolutely adviced to be done within a
Thread
or anAsyncTask
.Besides the response time, this is a Network Operation, so you'll need to do it outside the UI Thread.
Keep also in mind that every host has an associated IP address, but not every IP address has a reverse host, so that operation might fail and you need to handle that too.
The DNS server you'll query against is the one of your provider (or the client's provider if you're planning to run this within different clients). That means that not every result will be the same. For instance, your DNS server might not resolve the reverse host of an IP and a different DNS server might do.
The variable canonicalHostname
contains the result.
Use
holder.computerName.setText("Canonical : "+canonicalHostname);
This is because resolving a host name from an IP Address involves what is called a "Reverse DNS Lookup". The results of such a lookup will vary depending on the DNS server you are connecting to.
来源:https://stackoverflow.com/questions/21521844/how-to-resolve-network-host-names-from-ip-address