0

A particular website has 2 DNS entries, i.e. 2 IP addresses for same hostname. But, one of the IP address is not working, only 1 works.

I am trying to develop an HTTP Client without using HTTP libraries in Java. I am using Socket.connect(hostname, port) to connect to from my client to the server.

I am using InetSocketAddress to resolve the hostname. If it resolves to working IP Address my HTTP Client works fine. If the non working IP address is resolved, I get a Unknown Host Exception.

I am trying to handle this efficiently, i.e. when the non working IP address is selected, it should try to connect to another IP addresses. I am unable to achieve this. Appreciate all your help, thanks in advance.

1 Answers1

1

Use InetAddress.getAllByName(host) to get all addresses, then connect method of the Socket with timeout on one of addresses. If failed close socket and try another address

ZqBany
  • 201
  • 1
  • 5
  • It throws Unknown Host exception before timeout. In the catch block I am recursively calling the same connection method with index++ so that it tries to connect with next IP address. It does choose the right IP address with this flow, but throws an exception even for working IP address. If the working IP address is chosen first, it connects as expected. if non-working IP is chosen first, the catch block recursively calls the same method to work with next IP address (which works if chosen first), it throws an exception again. – Kunal Lakhwani Jan 31 '15 at 00:42
  • @KunalLakhwani Do you pass InetAdress to [socket constructor](http://download.java.net/jdk7/archive/b123/docs/api/java/net/Socket.html#Socket(java.net.InetAddress, int))? `InetAddress addresses[] = InetAddress.getAllByName(host);` and then use `new Socket(addresses[0], port)`? I think you use `new Socket(string)` and that constructor call `InetAddress.getByName(string)` so you get Unknown Host Exception – ZqBany Jan 31 '15 at 13:46