InetAddress getLocalHost() does not return expected IP address from C:\WINDOWS\system32\drivers\etc\hosts

Lars Andren picture Lars Andren · Apr 28, 2011 · Viewed 18.6k times · Source

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.

Answer

Bringer128 picture Bringer128 · Apr 28, 2011

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.