I have a Java application that needs to connect via sockets to two different servers on two separate machines. One server has been configured to listen on IPv4 connections, while the other has been configured to listen on IPv6 connections.
Now, assuming "host1" is the machine name of the server listening on IPv4 connections, while "host2" is the machine name of the server listening on IPv6 connections. I need to get an Inet4Address
for "host1" and an Inet6Address
for "host2" to create a socket connection to each server, such as the following:
Inet4Address inet4 = (Inet4Address)InetAddress.getByName("host1");
InetSocketAddress soc4 = new InetSocketAddress(inet4, 7777);
...
Inet6Address inet6 = (Inet6Address)InetAddress.getByName("host2");
InetSocketAddress soc6 = new InetSocketAddress(inet6, 7777);
...
However, the JVM by default prefers to use IPv4 addresses over IPv6 addresses for backward compatibility reasons. So, in the above code, the first attempt to connect to "host1" succeeds, but the second attempt to connect to "host2" fails because InetAddress.getByName("host2")
returns an Inet4Address
instead of Inet6Address
.
I understand that I can set the system property java.net.preferIPv6Addresses
to true to prefer IPv6 addresses over IPv4, but this in turn causes the second attempt to connect to "host2" succeeds, but the first attempt to connect to "host1" failed(!) because InetAddress.getByName("host1")
returns an Inet6Address
instead of Inet4Address
.
The system property java.net.preferIPv6Addresses
is only being read once (see InetAddress line 212-218) and so it would have no effects even if I change its value back to false after setting it to true.
So what I can I do in this case? This seems like a common problem, so surely there has to be a way already to do it.
Note that I can of course use InetAddress.getByAddress()
and supply each machine's IP address explicitly instead to get back an Inet4Address
and Inet6Address
, but I do not want to do this unless I really have to. So other solutions please.
Oh, I am using java 1.6.0_19 in case it matters.
Thanks!
static Inet6Address getInet6AddressByName(String host) throws UnknownHostException, SecurityException
{
for(InetAddress addr : InetAddress.getAllByName(host))
{
if(addr instanceof Inet6Address)
return (Inet6Address)addr;
}
throw new UnknownHostException("No IPv6 address found for " + host);
}