Cómo crear un programa que funcione como ‘rebote de IP’

Este es el programa para el rebote de ip en la red java y la programación de socket

/ **
* La biblioteca utillib.
* Más información está disponible en http://www.jinchess.com/.
* Copyright (C) 2002 Alexander Maryanovsky.
* Todos los derechos reservados.
* *
* La biblioteca utillib es software libre; puedes redistribuir
* y / o modificarlo bajo los términos de la Licencia Pública General Menor GNU
* según lo publicado por la Free Software Foundation; ya sea la versión 2 de la
* Licencia, o (a su elección) cualquier versión posterior.
* *
* La biblioteca utillib se distribuye con la esperanza de que lo hará
* sea útil, pero SIN NINGUNA GARANTÍA; sin siquiera la garantía implícita de
* COMERCIABILIDAD o APTITUD PARA UN PROPÓSITO EN PARTICULAR. Ver el GNU Lesser
* Licencia pública general para más detalles.
* *
* Debería haber recibido una copia de la Licencia pública general menor de GNU
* junto con la biblioteca utillib; si no, escriba al Software Libre
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 EE. UU.
* /

import java.io. *;
import java.net.Socket;
import java.net.ServerSocket;

/ **
* Implementa una utilidad de rebote TCP / IP (proxy). Ejecutas rebote especificando qué
* puerto para escuchar, qué host y en qué puerto conectarse y lo hará
* actuar como un proxy que transmite información entre cualquiera que se conecte a él y el
* servidor especificado.
* /

rebote de clase pública {

/ **
* El método principal.
* /

public static void main (String [] args) {
if (args.length <3) {
printUsage ();
System.exit (1);
}

int localPort;
tratar{
localPort = Integer.parseInt (args [0]);
} catch (NumberFormatException e) {
System.err.println (“Valor de puerto local incorrecto:” + args [0]);
printUsage ();
System.exit (2);
regreso;
}

Cadena hostname = args [1];

int remotePort;
tratar{
remotePort = Integer.parseInt (args [2]);
} catch (NumberFormatException e) {
System.err.println (“Valor de puerto remoto incorrecto:” + args [2]);
printUsage ();
System.exit (3);
regreso;
}

boolean shouldLog = args.length> 3? Boolean.valueOf (args [3]). BooleanValue (): falso;
int numConnections = 0;

tratar{
ServerSocket ssock = nuevo ServerSocket (localPort);
while (verdadero) {
Socket comingSock = ssock.accept ();
Socket outgoingSock = nuevo Socket (nombre de host, remotePort);
numConnections ++;

InputStream entrante = entranteSock.getInputStream ();
InputStream outgoingIn = outgoingSock.getInputStream ();
OutputStream entranteOut = entranteSock.getOutputStream ();
OutputStream outgoingOut = outgoingSock.getOutputStream ();

if (shouldLog) {
String comingLogName = “in-log -” + comingSock.getInetAddress (). GetHostName () + “(” + localPort + “) -” + numConnections + “.dat”;
Cadena outgoingLogName = “out-log-” + hostname + “(” + remotePort + “) -” + numConnections + “. Dat”;
OutputStream comingLog = nuevo FileOutputStream (comingLogName);
entrante = nuevo MultiOutputStream (entrante fuera, entrante registro);
OutputStream outgoingLog = nuevo FileOutputStream (outgoingLogName);
outgoingOut = nuevo MultiOutputStream (outgoingOut, outgoingLog);
}

PumpThread t1 = new PumpThread (entrante, saliente saliente);
PumpThread t2 = new PumpThread (outgoingIn, entranteOut);
t1.start ();
t2.start ();
}
} catch (IOException e) {
e.printStackTrace ();
System.exit (3);
}
}

/ **
* Vuelca la información de uso en la secuencia de error estándar.
* /

private static anular printUsage () {
System.err.println (“Utilidad de rebote”);
System.err.println (“Copyright (C) 2002 Alexander Maryanovsky”);
System.err.println ();
System.err.println (“Uso: java free.util.Bounce localPort hostname remotePort [shouldLog]”);
System.out.println ();
System.out.println (“Versión 1.01 – 31 de noviembre de 2002”);
}

}
/ **
* La biblioteca utillib.
* Más información está disponible en http://www.jinchess.com/.
* Copyright (C) 2002 Alexander Maryanovsky.
* Todos los derechos reservados.
* *
* La biblioteca utillib es software libre; puedes redistribuir
* y / o modificarlo bajo los términos de la Licencia Pública General Menor GNU
* según lo publicado por la Free Software Foundation; ya sea la versión 2 de la
* Licencia, o (a su elección) cualquier versión posterior.
* *
* La biblioteca utillib se distribuye con la esperanza de que lo hará
* sea útil, pero SIN NINGUNA GARANTÍA; sin siquiera la garantía implícita de
* COMERCIABILIDAD o APTITUD PARA UN PROPÓSITO EN PARTICULAR. Ver el GNU Lesser
* Licencia pública general para más detalles.
* *
* Debería haber recibido una copia de la Licencia pública general menor de GNU
* junto con la biblioteca utillib; si no, escriba al Software Libre
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 EE. UU.
* /

/ **
* Un OutputStream que transmite todos los datos escritos en un
* lista de OutputStreams dados.
* /

clase MultiOutputStream extiende OutputStream {

/ **
* Una matriz que contiene los OutputStreams a los que transmitimos datos.
* /

flujos finales privados de OutputStream [];

/ **
* Crea un nuevo MultiOutputStream que transmite datos al
* especificó dos OutputStreams . Cualquier valor nulo
* será ignorado en silencio.
* /

MultiOutputStream público (OutputStream out1, OutputStream out2) {
this (nuevo OutputStream [] {out1, out2});
}

/ **
* Crea un nuevo MultiOutputStream que transmite datos al
* OutputStreams especificado. Cualquier elemento null en el
* array será ignorado en silencio.
* /

MultiOutputStream público (streams OutputStream []) {
if (transmisiones == nulo)
lanzar nueva IllegalArgumentException (“La matriz especificada puede no ser nula”);

int cuenta = 0;
for (int i = 0; i <streams.length; i ++)
if (secuencias [i]! = nulo)
recuento ++;

this.streams = new OutputStream [cuenta];
cuenta = 0;
for (int i = 0; i <streams.length; i ++) {
OutputStream stream = streams [i];
if (flujo! = nulo)
this.streams [cuenta ++] = secuencia;
}
}

/ **
* Cierra todos los OutputStreams subyacentes.
* /

public void close () arroja IOException {
for (int i = 0; i <streams.length; i ++)
corrientes [i] .close ();
}

/ **
* Vacía todos los OutputStreams subyacentes.
* /

public void flush () arroja IOException {
for (int i = 0; i <streams.length; i ++)
corrientes [i] .flush ();
}

/ **
* Escribe el byte especificado en el subyacente
* OutputStreams .
* /

public void write (int b) arroja IOException {
for (int i = 0; i <streams.length; i ++)
corrientes [i] .write (b);
}

/ **
* Escribe la cantidad especificada de bytes de la matriz de bytes dada comenzando
* en el desplazamiento especificado al OutputStreams subyacente.
* /

Public Void Write (byte [] arr, int offset, int length) arroja IOException {
for (int i = 0; i <streams.length; i ++)
flujos [i] .write (arr, offset, length);
}

}
/ **
* La biblioteca utillib.
* Más información está disponible en http://www.jinchess.com/.
* Copyright (C) 2002 Alexander Maryanovsky.
* Todos los derechos reservados.
* *
* La biblioteca utillib es software libre; puedes redistribuir
* y / o modificarlo bajo los términos de la Licencia Pública General Menor GNU
* según lo publicado por la Free Software Foundation; ya sea la versión 2 de la
* Licencia, o (a su elección) cualquier versión posterior.
* *
* La biblioteca utillib se distribuye con la esperanza de que lo hará
* sea útil, pero SIN NINGUNA GARANTÍA; sin siquiera la garantía implícita de
* COMERCIABILIDAD o APTITUD PARA UN PROPÓSITO EN PARTICULAR. Ver el GNU Lesser
* Licencia pública general para más detalles.
* *
* Debería haber recibido una copia de la Licencia pública general menor de GNU
* junto con la biblioteca utillib; si no, escriba al Software Libre
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 EE. UU.
* /

/ **
* Un hilo que bombea la información leída de un flujo de entrada dado al
* flujo de salida dado.
* /

clase PumpThread extiende Thread {

/ **
* El InputStream.
* /

InputStream final privado en;

/ **
* El OutputStream.
* /

Salida final privada Salida de flujo;

/ **
* El buffer que estamos usando.
* /

búfer final privado byte [];

/ **
* La IOException lanzada al leer o escribir información, o nula si
* ninguna.
* /

excepción privada IOException;

/ **
* Crea un nuevo PumpThread que bombeará información del dado
* InputStream en el OutputStream dado.
* /

Public PumpThread (InputStream in, OutputStream out) {
esto (adentro, afuera, 2048);
}

/ **
* Crea un nuevo PumpThread que bombeará información del dado
* InputStream en el OutputStream dado y utilizará un búfer del dado
* Talla.
* /

Public PumpThread (InputStream in, OutputStream out, int bufSize) {
this (entrada, salida, nuevo byte [bufSize]);
}

/ **
* Crea un nuevo PumpThread que bombeará información del dado
* InputStream en el OutputStream dado y usará el búfer dado.
* /

Public PumpThread (InputStream in, OutputStream out, byte [] buffer) {
this.in = in;
this.out = out;
this.buffer = buffer;
}

/ **
* Hace el bombeo real.
* /

public void run () {
tratar{
while (verdadero) {
int cuenta = in.read (buffer);
si (cuenta <= 0)
regreso;
out.write (buffer, 0, cuenta);
}
} catch (IOException e) {
excepción = e;
}
}

/ **
* Devuelve la excepción lanzada mientras lee o escribe, o null
* si terminó normalmente, sin lanzar una excepción (lectura devuelta -1).
* *
* @throws IllegalStateException si el hilo sigue vivo.
* /

public IOException getException () {
if (isAlive ())
lanzar nueva IllegalStateException (“El hilo todavía está vivo”);

excepción de retorno;
}

}