A Java application that wants to use both Inet4Address and Inet6Address at the same time

I have a Java application that needs to be connected through sockets to two different servers on two separate machines. One server is configured to listen on IPv4 connections, and the other is configured to listen on IPv6 connections.

Now, considering that "host1" is the name of the computer for the server listening on IPv4 connections, while "host2" is the name of the computer on the server listening on IPv6 connection. I need to get Inet4Addressfor "host1" and Inet6Addressfor "host2" to create a socket connection to each server, for example 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. Thus, in the above code, the first attempt to connect to "host1" succeeds, but the second attempt to connect to "host2" fails because it InetAddress.getByName("host2")returns Inet4Addressinstead Inet6Address.

I understand that I can set the system property java.net.preferIPv6Addressesto true to prefer IPv6 addresses over IPv4, but this, in turn, leads to a successful attempt to connect to "host2", but the first attempt to connect to "host1" failed (!), Because which InetAddress.getByName("host1")returns Inet6Addressinstead Inet4Address.

java.net.preferIPv6Addresses (. InetAddress 212-218), , false true.

, ? , .

, , , InetAddress.getByAddress() IP- , Inet4Address Inet6Address, , . , .

, java 1.6.0_19, .

!

+5
3
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);
}
+5

, Inet6Address Inet4Address, , InetAddress.

CCE.

IPv6 IPv4.

, IPv6 IPv4, , IPv4- IPv6.


:

0

Inet6Address.getAllByName("host2").

IPv6 addres , .

0

All Articles