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.