Search code examples
javanetwork-programmingip-addresslocalhostinetaddress

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


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.


Solution

  • 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.