diff --git a/src/main/java/moe/nekojimi/chords/LocalBindSocketFactory.java b/src/main/java/moe/nekojimi/chords/LocalBindSocketFactory.java index 09e1d06..b4bd8eb 100644 --- a/src/main/java/moe/nekojimi/chords/LocalBindSocketFactory.java +++ b/src/main/java/moe/nekojimi/chords/LocalBindSocketFactory.java @@ -17,10 +17,7 @@ package moe.nekojimi.chords; import java.io.IOException; -import java.net.InetAddress; -import java.net.ServerSocket; -import java.net.Socket; -import java.net.UnknownHostException; +import java.net.*; import javax.net.SocketFactory; /** @@ -42,6 +39,18 @@ public class LocalBindSocketFactory extends SocketFactory this.localAddress = localAddress; } + @Override + public Socket createSocket() throws IOException + { + return new LocalBoundSocket(); +// throw new RuntimeException("Trying to create an empty socket!"); + } + + private InetSocketAddress findFreeSocketAddress() + { + return new InetSocketAddress(localAddress, findFreePort(localAddress)); + } + @Override public Socket createSocket(String remoteAddr, int remotePort) throws IOException, UnknownHostException { @@ -63,7 +72,10 @@ public class LocalBindSocketFactory extends SocketFactory @Override public Socket createSocket(InetAddress remoteAddr, int remotePort, InetAddress x, int localPort) throws IOException { - return new Socket(remoteAddr, remotePort, localAddress, localPort); + System.out.println("Requested socket; " + localAddress + ":" + localPort + " -> " + remoteAddr + ":" + remotePort); + Socket socket = new Socket(remoteAddr, remotePort, localAddress, localPort); + System.out.println("Returned socket; " + socket.getLocalSocketAddress() + ":" + socket.getLocalPort() + " -> " + socket.getRemoteSocketAddress() + ":" + socket.getPort()); + return socket; } private static int findFreePort(InetAddress localAddr) @@ -85,4 +97,16 @@ public class LocalBindSocketFactory extends SocketFactory throw new RuntimeException("Could not find a free port"); } + private class LocalBoundSocket extends Socket + { + + @Override + public void bind(SocketAddress bindpoint) throws IOException + { + InetSocketAddress localAddress = findFreeSocketAddress(); + System.err.println("LocalBoundSocket NOT binding to " + bindpoint + ", using " + localAddress + " instead!"); + super.bind(localAddress); + } + } + }