Search code examples
javaandroidnetworkinghostinetaddress

Why is Java's InetAddress getHostName() not giving me the host's name?


I'm trying to get the device's name using its local IP address on the network. Is this how I'm supposed to do it? ex) Arnold-PC, andoid-nnnnnnnnnn

String name = InetAddress.getByName(ip).getHostName();
System.out.println(name);

The above should give me the host's name... but instead gives me the local IP address. - 192.168.2.101

as per the documentation...

public String getHostName ()

Returns the host name corresponding to this IP address. This may or may not be a fully-qualified name. If the IP address could not be resolved, the numeric representation is returned instead

Why is it not able to find the host's name?

I don't know much about computer networking... so please excuse my ignorance. :P


Solution

  • check in the command prompt whether you can able to resolve the ip address using nsloookup

    if you can't, then your DNS broken

    I would like to quote the few lines from java documentation here

    getCanonicalHostName() Gets the fully qualified domain name for this IP address. Best effort method, meaning we may not be able to return the FQDN depending on the underlying system configuration.

    one more trick is to edit host file to get output (not recommended)

    Have a look in this answer too

    link