Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- import java.util.ArrayList;
- import java.util.Iterator;
- import java.net.*;
- import java.nio.ByteBuffer;
- public class Rip {
- public static ArrayList<InetAddress> vecinos = new ArrayList<InetAddress>();
- public static String ipArchivo;
- public static ArrayList<Tabla> tabla = new ArrayList<Tabla>();
- public static void main (String args[]) throws Exception {
- String vecino, vlan;
- int len;
- long time;
- boolean igual = false;
- //Creamos el socketServidor de tipo DatagramSocket en el puerto 520. Todos los datos
- //enviados y recibidos pasaran a traves de este socket. Ya que UDP es un servicio
- //sin conexion, no tenemos crear un nuevo socket
- ipArchivo = InetAddress.getLocalHost().getHostAddress();
- int mask = 0xffffffff << (32 - 32);
- int value =mask;
- byte[] bytes = new byte[]{
- (byte)(value >>> 24), (byte)(value >> 16 & 0xff), (byte)(value >> 8 & 0xff), (byte)(value & 0xff)};
- InetAddress netAddr = InetAddress.getByAddress(bytes);
- InetAddress ipArchivo2 = InetAddress.getByName(ipArchivo);
- tabla.add(new Tabla(ipArchivo2,netAddr,ipArchivo2,0)); //En el siguiente salto seria un 0
- DatagramSocket socketServidor = new
- DatagramSocket(520);
- //Abrimos el fichero de configuracion y lo leemeos
- FileInputStream ficheroConf = new FileInputStream ("ripconf-"+InetAddress.getLocalHost().getHostAddress()+".txt");
- BufferedReader init ;
- String linea;
- String aux="/";
- try{
- InetAddress ip = InetAddress.getByName(ipArchivo);
- init = new BufferedReader(new InputStreamReader(ficheroConf));
- linea= init.readLine();
- System.out.println("HOLA:"+linea.toString());
- do{
- if (!linea.contains(aux)){
- vecinos.add(InetAddress.getByName(linea));
- }else{
- System.out.println("VLAN"+linea);
- vlan =linea.substring(0,linea.indexOf(aux)).trim();
- System.out.println(vlan);
- len=Integer.parseInt(linea.substring(linea.indexOf(aux)+1));
- InetAddress mas = obtenerMascara(len);
- tabla.add(new Tabla(InetAddress.getByName(vlan),mas,ip,1));
- }
- }while((linea=init.readLine()) != null);
- init.close();
- }catch(IOException | NullPointerException mes){
- }
- byte[] recibirDatos = null;
- byte[] enviarDatos = null;
- while (true){
- socketServidor.setSoTimeout(3000);
- time=System.currentTimeMillis();
- try{
- byte[] buffer;
- while(true){
- DatagramPacket recibirPaquete=null;
- buffer =new byte[504];
- recibirPaquete =
- new DatagramPacket (buffer, buffer.length);
- socketServidor.receive(recibirPaquete);
- if(recibirPaquete!=null){
- System.out.println("Paquete recibido");
- leerpaquete(recibirPaquete);
- socketServidor.setSoTimeout(3000-(int)(System.currentTimeMillis()-time));
- //enviarTabla();
- }
- }
- }catch(SocketTimeoutException mes1){
- enviarTabla();
- }
- }
- }
- //ByteBuffer es una clase
- public static void enviarTabla() throws IOException{
- String campoCero="0";
- String campoDos="2"; //Se utilizara para el comando para la version y para el campo
- String ip,mascara,nextHop;
- byte num1=0, num2=2;
- int metrica;
- byte[] buffer=null;
- //IMPRIMIREMOS LA TABLA DE ENCAMINAMIENTO AQUI
- //Cada tabla estarĂ¡ compuesta por los datos : Comando Version 0
- try{
- DatagramSocket cliente = new DatagramSocket();
- DatagramPacket datos;
- InetAddress dir;
- Iterator<InetAddress> it = vecinos.iterator();
- while (it.hasNext()){
- InetAddress IpVecino = it.next();
- Iterator <Tabla> itTab = tabla.iterator();
- buffer = concat (ByteBuffer.allocate(1).put(num2).array(),ByteBuffer.allocate(1).put(num2).array(),ByteBuffer.allocate(2).put(num1).array());
- while (itTab.hasNext()){
- Tabla tab = itTab.next();
- if(!(tab.getNextHop().equals(IpVecino) ||tab.getIp().equals(IpVecino))){
- buffer = concat ( buffer, ByteBuffer.allocate(2).put(num2).array(),ByteBuffer.allocate(2).put(num1).array(),
- ByteBuffer.allocate(4).put(tab.getIp().getAddress()).array(),
- ByteBuffer.allocate(4).put(tab.getMask().getAddress()).array(),
- ByteBuffer.allocate(4).put(tab.getNextHop().getAddress()).array(),
- ByteBuffer.allocate(4).putInt(tab.getMetrica()).array());
- }
- System.out.println(tab);
- }
- datos=new DatagramPacket (buffer,buffer.length,IpVecino,520);
- cliente.send(datos);
- System.out.println("paquete enviado");
- }
- }catch(SocketException mes1){
- }
- }
- //Funciona que concatena todos los arrays de bytes que se pasa para construir el paquete RIP
- public static byte[] concat(byte[]...arrays){
- // Determine the length of the result array
- int totalLength = 0;
- for (int i = 0; i < arrays.length; i++)
- {
- totalLength += arrays[i].length;
- }
- // create the result array
- byte[] result = new byte[totalLength];
- // copy the source arrays into the result array
- int currentIndex = 0;
- for (int i = 0; i < arrays.length; i++)
- {
- System.arraycopy(arrays[i], 0, result, currentIndex, arrays[i].length);
- currentIndex += arrays[i].length;
- }
- return result;
- }
- //FUNCION QUE SE LE PASA LA MASCARA Y TE DEVUELVE EL CIDR
- public static InetAddress obtenerMascara(int len) throws UnknownHostException{
- int mask = 0xffffffff << (32 - len);
- int value =mask;
- byte[] bytes = new byte[]{
- (byte)(value >>> 24), (byte)(value >> 16 & 0xff), (byte)(value >> 8 & 0xff), (byte)(value & 0xff)};
- InetAddress netAddr = InetAddress.getByAddress(bytes);
- return netAddr;
- }
- //LEER PAQUETE
- public static void leerpaquete(DatagramPacket dp){
- InetAddress ipvecino = dp.getAddress();
- byte[] bytes = dp.getData();
- int i;
- InetAddress ip,mascara,ssalto;
- byte[] buffer;
- for( i=8;i<bytes.length;i+=20){
- try {
- boolean meterTabla=false;
- if(bytes[i-3] !=2 && bytes[i-4] !=2)
- break;
- buffer = new byte[]{bytes[i],bytes[i+1],bytes[i+2],bytes[i+3]};
- ip = InetAddress.getByAddress(buffer);
- buffer = new byte[]{bytes[i+4],bytes[i+5],bytes[i+6],bytes[i+7]};
- mascara = InetAddress.getByAddress(buffer);
- buffer = new byte[]{bytes[i+8],bytes[i+9],bytes[i+10],bytes[i+11]};
- ssalto = InetAddress.getByAddress(buffer);
- buffer = new byte[]{bytes[i+12],bytes[i+13],bytes[i+14],bytes[i+15]};
- int metrica= (buffer[0]<<24) &0xff000000 | (buffer[1]<<16) &0x00ff0000 | (buffer[2]<< 8) &0x0000ff00 | (buffer[3]<< 0) &0x000000ff;
- tabla.get(0).setTime(System.currentTimeMillis());// Nunca se borra la priemra entrada
- Tabla nueva = new Tabla(ip,mascara,ssalto,metrica+1);
- ArrayList<Tabla> tabla2 = new ArrayList<Tabla>(tabla);
- Iterator<Tabla> nuevaentrada = tabla2.iterator();
- int contador=0;
- while(nuevaentrada.hasNext()){
- Tabla auxiliar = nuevaentrada.next();
- System.out.println("1"+auxiliar.getIp());
- System.out.println("2"+nueva.getIp());
- if(auxiliar.getIp().equals(nueva.getIp()) && (auxiliar.getMask().equals(nueva.getMask()))){
- if(auxiliar.getMetrica() == (nueva.getMetrica())){
- if(System.currentTimeMillis() - nueva.getTime()>90000){
- tabla.remove(contador);
- tabla.add(nueva);
- meterTabla=false;
- break;
- }
- }
- else if(auxiliar.getMetrica() > (nueva.getMetrica())){
- tabla.remove(contador);
- tabla.add(nueva);
- meterTabla=false;
- break;
- }
- }else{
- meterTabla=true;
- }
- contador++;
- }
- if(meterTabla){
- tabla.add(nueva);
- }
- } catch (UnknownHostException e) {
- e.printStackTrace();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement