InetAddress.getAllByName- the order of ip addresses
I have a dns server such configured that it returns the ip addresses in a loop i.e.
if u first hit the dns it will return Adresses: first-ip , second-ip and if hit again wil return secondip,firstip. To get this try nslookup voiceservices.mcleodusa.com on command prompt twice in succession.
Now when i am using InetAddress.getByName or InetAddress.getAllByName it always returns me first-ip first. So i looked in to source code of java.net.InetAddress and found that most of the work is done by NameService class which comes from some package of sun.
Apparently what i wanted was the same effect that is happening on command prompt.
So i got little help and knew about dnsjava (http://www.dnsjava.org/index.html) . so i tried to use the Address class provided by dnsjava .But again the problem here comes that they are having a default cache in which they do not lookup again until jvm is shutdown.
So i took the code of Address class and changed it to my use and removed the default caching which fortunately came good and the results were satisfactory.
public static InetAddress []
getAllByName(String name) throws UnknownHostException {
Record [] records = lookupHostName(name);
InetAddress [] addrs = new InetAddress[records.length];
for (int i = 0; i < records.length; i++)
addrs = addrFromRecord(name, records);
return addrs;
}
private static Record []
lookupHostName(String name) throws UnknownHostException {
try {
Lookup freshLookup=new Lookup(name);
//this line is the only change from the code from Address class
// to fetch everytime fresh values
freshLookup.setCache(null);
Record [] records = freshLookup.run();
if (records == null)
throw new UnknownHostException("unknown host");
return records;
} catch (TextParseException e) {
throw new UnknownHostException("invalid name");
}
}
private static InetAddress
addrFromRecord(String name, Record r) throws UnknownHostException {
ARecord a = (ARecord) r;
return InetAddress.getByAddress(name, a.getAddress().getAddress());
}
Now what i would like to know if there is a better way to do it or there is any other Api available which do all of this by itself.

