3

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

God Usopp
  • 331
  • 1
  • 6
  • 18
  • is `nslookup` from the commandline able to determine the name ? – Marged Dec 23 '15 at 13:46
  • Does this answer your question? [Cannot get hostname from getHostName](https://stackoverflow.com/questions/1899288/cannot-get-hostname-from-gethostname) – Devabc Nov 28 '21 at 21:55

2 Answers2

0

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

Community
  • 1
  • 1
Pandiyan Cool
  • 6,381
  • 8
  • 51
  • 87
  • I've looked into nslookup and tried "nslookup launchmodem.com" as this is the domain I get from ipconfig. Is that what you meant? If my DNS is broken, is there another way to grab a hosts name? Is it possible to ask the router for the DHCP table? – God Usopp Dec 23 '15 at 14:28
  • If my DNS is broken, is there anything I can do about it? – God Usopp Dec 24 '15 at 06:11
  • Try flushing the DNS cache, from a cmd prompt – Pandiyan Cool Dec 24 '15 at 07:15
  • "ipconfig /flushdns" same result. I wonder if there would be a way to get JNetPCap on android... surely we could use JNetPCap to find the hostname of devices on a network? – God Usopp Dec 24 '15 at 11:43
0

From the docs

If this InetAddress was created with a host name, this host name will be remembered and returned; otherwise, a reverse name lookup will be performed and the result will be returned based on the system configured name lookup service. If a lookup of the name service is required, call getCanonicalHostName.

It seems like plain getHostName() won't look up the name if it can't reach out to a DNS server. The DNS server is what will give a name to the host IP address, just like a phone book. Give getCanonicalHostName() a try.

lase
  • 2,508
  • 2
  • 24
  • 35