From 0c29d56317c2dd4250d4bc19b316369ae09a315d Mon Sep 17 00:00:00 2001 From: Nekojimi Date: Fri, 3 Mar 2023 23:34:49 +0000 Subject: [PATCH] Made LocalBindSocketFactory much more hardcore. --- .../chords/LocalBindSocketFactory.java | 34 ++++++++++++++++--- 1 file changed, 29 insertions(+), 5 deletions(-) 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); + } + } + }