4

In the file C:\WINDOWS\system32\drivers\etc\hosts I have only the following line

192.168.0.23    computername.domain.com   computername

When I run

InetAddress localhost = InetAddress.getLocalHost();
System.out.println("getLocalHost:" + localhost);

I would expect the output to be

getLocalHost:computername/192.168.0.23

but it comes out as

getLocalHost:computername/192.168.0.107

Any ideas on why this happens? Should the configuration be made in some other file (too)?

EDIT

InetAddress.getByName('computername')

produces the same IP as getLocalHost() does.

Lars Andren
  • 8,601
  • 7
  • 41
  • 56
  • 2
    Why would you expect the entry from the hosts file to affect the IP address for localhost? I'd expect if you do a InetAddress.getByName('computername'), that would give you the IP address you want. – no.good.at.coding Apr 28 '11 at 03:19

2 Answers2

15

getLocalHost() returns the actual IP of one of your network adapters. If you do ipconfig in your command line one of your adapters should return the same address.

If you have multiple adapters and want a specific one, you will need to use NetworkInterface.getNetworkInterfaces() and then pull the list of InetAddresses from each interface.

  • Yep, in general `InetAddress.getLocalHost()` should be avoided. People simply have to realize that the answer from that method only HAPPENS to give the result you expect. Scenario: Your app has worked fine for years. Then you move it to a multi-homed host and bang! It stops working as you expect. Morale: don't rely on `InetAddress.getLocalHost()` for anything but textual info. I've upvoted this answer. – peterh Oct 03 '13 at 07:19
4

Why would entries from the hosts file affect the IP address for localhost?

InetAddress.getByName('computername') should give you the IP address you expect.

no.good.at.coding
  • 20,221
  • 2
  • 60
  • 51
  • 1
    Thanks for the help, but nope, it gives the same one as getLocalHost() – Lars Andren Apr 28 '11 at 03:51
  • It may, but may not. Hosts file is not the only, and not always the main source of name-to-address mapping. Under windows you have DNS and WINS, at least. – Vladimir Dyuzhev Apr 28 '11 at 04:04
  • On Windows, I believe the hosts file entry will be the first thing looked up for name resolution, which is why most anti-malware software will add a loopback address mapping for known malware serving hosts in the hosts file, thus preventing browsing to that domain name. [Not definitive but the first source I found].(http://vlaurie.com/computers2/Articles/hosts.htm) – no.good.at.coding Apr 28 '11 at 04:43