user1071840
user1071840

Reputation: 3592

IPv6 only socket in java

Is it possible to create a socket in java that binds only to ipv6 addresses?

I want to know if I can have 2 sockets on a machine such that one binds to ipv4 addresses and the other binds to ipv6 addresses only. Networking IPv6 User Guide for JDK/JRE 5.0 explains how ipv6 works on a Java platform but doesn't say anything about ipv6 only sockets. Are they even possible? I can't set the global IPV6_V6ONLY property.

Upvotes: 2

Views: 6359

Answers (2)

Zaboj Campula
Zaboj Campula

Reputation: 3360

I needed the same - to have separate tcp sockets (IPv4 and IPv6) that listen at the same port number. The only solution that I found is to create a pair of sockets (IPv4 and IPv6) for each address at the host.

For sake of simplicity the following code is limited to listen on localhost only. It creates two ServerSocket instances. One of then is bound to IPv4 localhost and one of them is bound to IPv6 localhost.

import java.io.*;
import java.net.*;

public class DualSock implements Runnable {

    ServerSocket s;
    String ver;
    static final int port = 1234;

    public void run() {
        while (true) {
            try {
               Socket client = s.accept();
               System.out.println("Connection over " + ver + " from " + client.getRemoteSocketAddress());
               client.close();
            } catch (Exception e) {
               System.out.println(e);
               System.exit(1);
            }
        }
    }

    public DualSock(ServerSocket s, String ver) {
       this.s = s;
       this.ver = ver;
    }

    public static void main(String argv[]) throws Exception {
        InetAddress address4 = InetAddress.getByName("127.0.0.1");
        ServerSocket server4 = new ServerSocket(port, 5, address4);
        DualSock ip4app = new DualSock(server4, "IPv4");

        InetAddress address6 = InetAddress.getByName("::1");
        ServerSocket server6 = new ServerSocket(port, 5, address6);
        DualSock ip6app = new DualSock(server6, "IPv6");

        new Thread(ip4app).start();
        new Thread(ip6app).start();
    }
}

It is not very useful to limit communication to localhost. A real application needs enumerate network interfaces, get their addresses and then create a ServerSocket for each address at the host.

Upvotes: 2

Caffeinated
Caffeinated

Reputation: 12484

The thing about IPV6 , is that is only compatible with IPV6 .

Which is the drawback of IPv6

As of 2014:

IPv4, which still carries more than 96% of Internet traffic worldwide

source

Upvotes: 0

Related Questions