Im folgenden ein einfacher TcpProxy in Java, welcher eingehende Verbindungen an eine andere Adresse / Port weiterleitet.
import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; public class TcpProxy { static class Listener extends Thread { final ServerSocket server; final String remoteHost; final int remotePort; Listener(ServerSocket server, String remoteHost, int remotePort) { this.server = server; this.remoteHost = remoteHost; this.remotePort = remotePort; } public void run() { try { while (true) { try { Socket client = server.accept(); System.out.println("accepted connection from " + client.getInetAddress() + ":" + client.getPort()); new Connection(client, remoteHost, remotePort).start(); } catch (Exception e) { e.printStackTrace(); } } } finally { System.exit(0); } } } static class Connection extends Thread { final Socket client; final Socket target; final InputStream clientIn; final InputStream targetIn; final OutputStream clientOut; final OutputStream targetOut; Connection(Socket client, String remoteHost, int remotePort)throws Exception { this.client = client; try { clientIn = client.getInputStream(); clientOut = client.getOutputStream(); target = new Socket(remoteHost, remotePort); try { targetIn = target.getInputStream(); targetOut = target.getOutputStream(); } catch (Exception e) { try { target.close(); } catch (Throwable t) { // } throw e; } } catch (Exception e) { try { client.close(); } catch (Throwable t) { // } throw e; } } public void run() { byte buf[] = new byte[4096]; int av, r; while (true) { try { av = clientIn.available(); if (av > 0) { r = clientIn.read(buf); targetOut.write(buf, 0, r); } av = targetIn.available(); if (av > 0) { r = targetIn.read(buf); clientOut.write(buf, 0, r); } Thread.sleep(1); if (target.isClosed() || !target.isConnected() || client.isClosed() || !client.isConnected()) { System.out.println("closed connection from " + client.getInetAddress() + ":" + client.getPort()); try { target.close(); } catch (Throwable t) { // } try { client.close(); } catch (Throwable t) { // } } } catch (Exception e) { e.printStackTrace(); } } } } /** * * @param args * @throws IOException */ public static void main(String args[]) throws IOException { int localPort = Integer.parseInt(args[0]); String remoteHost = args[1]; int remotePort = Integer.parseInt(args[2]); System.out.println("TCP proxy"); System.out.println("local port: " + localPort); System.out.println("remote host: " + remoteHost); System.out.println("remote port: " + remotePort); ServerSocket server = new ServerSocket(localPort, 50); new Listener(server, remoteHost, remotePort).start(); } }

