Reputation: 941
My Host entry as follow :
10.106.1.188 myhost
192.168.0.156 myhost
192.168.0.160 myhost
192.168.0.150 myhost
10.106.1.121 myhost
10.106.1.110 myhost
I use following code for get all IP Address from host entry
InetAddress[] addresses = InetAddress.getAllByName("myhost");
for( InetAddress address : addresses) {
System.out.println(address);
}
Problem is above code does not manage Ip Address order.
When Running above program on Windows 7 it works fine but on linux machine it does not manage order
Upvotes: 0
Views: 1124
Reputation: 6240
I have similar problem on Windows machine with multiple interfaces (IP addresses). What I noticed that inetAddress.getAllByName()
function returns list of IPs accordingly their interface ID i.e. the topmost IP in the list will be the IP of the interface with highest ID (OS specific internal list). You could lookup the list of interfaces via command in Windows cmd line: route print
Interface List 7...02 00 xx xx xx xx ......Microsoft KM-TEST Loopback Adapter 3...fc aa xx xx xx xx ......Intel(R) Ethernet Connection I217-V 8...02 01 xx xx xx xx ......SAMSUNG Mobile USB Remote NDIS Network Device 4...00 e0 xx xx xx xx ......Realtek PCI GBE Family Controller . . . . . 9...00 00 00 00 00 00 00 e0 Microsoft ISATAP Adapter #3 32...00 00 00 00 00 00 00 e0 Microsoft ISATAP Adapter #4
Thus in this example, first IP in the list of getAllByName()
call will be IP of the interface 8 (SAMSUNG Mobile USB Remote...).
Upvotes: 0
Reputation: 19445
The order of addresses returned by java.net.InetAddress.getAllByName is undefined. If it works on one platform for you then it's just a happy accident.
Remember that the results may not always come from a hosts file, but from the result of a DNS lookup (where the order is also undefined).
Upvotes: 1
Reputation: 771
I would suggest Use Comparator which should sort the IP address for you. other wise you will get platform dependent results. Here is one example http://thilosdevblog.wordpress.com/2010/09/15/sorting-ip-addresses-in-java/ This example keeps Ordering intact.
Upvotes: 2