If I make a connection using new Socket("unit.domain.com", 100)
and the unit.domain.com
DNS record has multiple IP addresses in the A record.. In the event of a failed connection, Does Java automatically connect to one of the other addresses in the list like the browser does? or does that have to be implemented manually?
Asked
Active
Viewed 2,233 times
4

700 Software
- 85,281
- 83
- 234
- 341
1 Answers
5
No! Creating a socket via new Socket(String, int) results in a resolving like that
addr = InetAddress.getByName(hostname);
which is a shortcut for
return InetAddress.getAllByName(host)[0];
The address resolution is performed in the Socket c-tor.
If you have to reconnect (failover) use the result returned by InetAddress.getAllByName(host), randomize (or use round-robin) and connect to the necessary addresses.
Edit: also if you are going to need to connect with some likely failure, you'd be better off using connect method of the Socket class with a timeout. Also make sure you close even failed sockets (and esp. channels) since they may leak a FD on *Nix.

bestsss
- 11,796
- 3
- 53
- 63
-
OK, it's about time I asked. What's *Nix? – 700 Software Jan 12 '11 at 17:36
-
It stands for "unix alike", closing sockets on linux/unix is two phase operation and due to some shortcomings, the 2nd phase may not complete and leave a notorious FD leak unless proper invoke of close() happens. So make sure to close any SocketChannel (Socket) regardless if connect() succeeds – bestsss Jan 12 '11 at 22:33