Recover Outgoing TCP Connection in Java Based on Multiple DNS Results

If I make a connection using new Socket("unit.domain.com", 100) and the DNS record unit.domain.com has several IP addresses in the A record. If the connection fails, does Java automatically connect to one of the others addresses in the list how does the browser do? or does it need to be done manually?

+4
source share
1 answer

No! Creating a socket through a new Socket (String, int) results in a resolution such that

 addr = InetAddress.getByName(hostname); 

which is a shortcut for

 return InetAddress.getAllByName(host)[0]; 

Address resolution is done in the C-tor Socket.

If you need to reconnect (switching to another resource), use the result returned by InetAddress.getAllByName (host), randomize (or use circular) and connect to the necessary addresses.

Edit: Also, if you need to connect with some likely failure, you better use the Socket class connection method with a timeout. Also make sure that you close even bad sockets (and esp. Channels), as FD on * Nix can leak.

+5
source

Source: https://habr.com/ru/post/1334945/


All Articles