jQuery in Action, 2nd edition
The moose likes Sockets and Internet Protocols and the fly likes Using both Inet4Address and Inet6Address in a single Java application Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Sockets and Internet Protocols
Reply Bookmark "Using both Inet4Address and Inet6Address in a single Java application" Watch "Using both Inet4Address and Inet6Address in a single Java application" New topic
Author

Using both Inet4Address and Inet6Address in a single Java application

Hansen Candrawinata
Greenhorn

Joined: Nov 30, 2008
Posts: 10
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:



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.
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: Using both Inet4Address and Inet6Address in a single Java application
 
Similar Threads
MYSQL on IPV6
Problem with simple chat app
Support for IPv6
function for IP address to integer conversion
Server Host/Port Validation