Advertisement
Guest User

Untitled

a guest
May 24th, 2015
210
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.68 KB | None | 0 0
  1. import java.io.*;
  2. import java.util.ArrayList;
  3. import java.util.Iterator;
  4. import java.net.*;
  5. import java.nio.ByteBuffer;
  6. public class Rip {
  7.  
  8.  
  9. public static ArrayList<InetAddress> vecinos = new ArrayList<InetAddress>();
  10. public static String ipArchivo;
  11. public static ArrayList<Tabla> tabla = new ArrayList<Tabla>();
  12. public static void main (String args[]) throws Exception {
  13. String vecino, vlan;
  14. int len;
  15. long time;
  16. boolean igual = false;
  17. //Creamos el socketServidor de tipo DatagramSocket en el puerto 520. Todos los datos
  18. //enviados y recibidos pasaran a traves de este socket. Ya que UDP es un servicio
  19. //sin conexion, no tenemos crear un nuevo socket
  20. ipArchivo = InetAddress.getLocalHost().getHostAddress();
  21. int mask = 0xffffffff << (32 - 32);
  22. int value =mask;
  23. byte[] bytes = new byte[]{
  24. (byte)(value >>> 24), (byte)(value >> 16 & 0xff), (byte)(value >> 8 & 0xff), (byte)(value & 0xff)};
  25. InetAddress netAddr = InetAddress.getByAddress(bytes);
  26. InetAddress ipArchivo2 = InetAddress.getByName(ipArchivo);
  27. tabla.add(new Tabla(ipArchivo2,netAddr,ipArchivo2,0)); //En el siguiente salto seria un 0
  28. DatagramSocket socketServidor = new
  29. DatagramSocket(520);
  30. //Abrimos el fichero de configuracion y lo leemeos
  31. FileInputStream ficheroConf = new FileInputStream ("ripconf-"+InetAddress.getLocalHost().getHostAddress()+".txt");
  32. BufferedReader init ;
  33. String linea;
  34. String aux="/";
  35.  
  36. try{
  37. InetAddress ip = InetAddress.getByName(ipArchivo);
  38. init = new BufferedReader(new InputStreamReader(ficheroConf));
  39. linea= init.readLine();
  40. System.out.println("HOLA:"+linea.toString());
  41. do{
  42. if (!linea.contains(aux)){
  43. vecinos.add(InetAddress.getByName(linea));
  44. }else{
  45. System.out.println("VLAN"+linea);
  46. vlan =linea.substring(0,linea.indexOf(aux)).trim();
  47. System.out.println(vlan);
  48. len=Integer.parseInt(linea.substring(linea.indexOf(aux)+1));
  49. InetAddress mas = obtenerMascara(len);
  50. tabla.add(new Tabla(InetAddress.getByName(vlan),mas,ip,1));
  51. }
  52. }while((linea=init.readLine()) != null);
  53. init.close();
  54. }catch(IOException | NullPointerException mes){
  55.  
  56. }
  57. byte[] recibirDatos = null;
  58. byte[] enviarDatos = null;
  59. while (true){
  60. socketServidor.setSoTimeout(3000);
  61. time=System.currentTimeMillis();
  62. try{
  63. byte[] buffer;
  64. while(true){
  65.  
  66. DatagramPacket recibirPaquete=null;
  67. buffer =new byte[504];
  68. recibirPaquete =
  69. new DatagramPacket (buffer, buffer.length);
  70. socketServidor.receive(recibirPaquete);
  71.  
  72. if(recibirPaquete!=null){
  73. System.out.println("Paquete recibido");
  74. leerpaquete(recibirPaquete);
  75. socketServidor.setSoTimeout(3000-(int)(System.currentTimeMillis()-time));
  76. //enviarTabla();
  77. }
  78. }
  79. }catch(SocketTimeoutException mes1){
  80. enviarTabla();
  81. }
  82. }
  83. }
  84.  
  85. //ByteBuffer es una clase
  86. public static void enviarTabla() throws IOException{
  87. String campoCero="0";
  88. String campoDos="2"; //Se utilizara para el comando para la version y para el campo
  89. String ip,mascara,nextHop;
  90. byte num1=0, num2=2;
  91. int metrica;
  92. byte[] buffer=null;
  93. //IMPRIMIREMOS LA TABLA DE ENCAMINAMIENTO AQUI
  94. //Cada tabla estarĂ¡ compuesta por los datos : Comando Version 0
  95. try{
  96. DatagramSocket cliente = new DatagramSocket();
  97. DatagramPacket datos;
  98. InetAddress dir;
  99. Iterator<InetAddress> it = vecinos.iterator();
  100. while (it.hasNext()){
  101. InetAddress IpVecino = it.next();
  102. Iterator <Tabla> itTab = tabla.iterator();
  103. buffer = concat (ByteBuffer.allocate(1).put(num2).array(),ByteBuffer.allocate(1).put(num2).array(),ByteBuffer.allocate(2).put(num1).array());
  104. while (itTab.hasNext()){
  105. Tabla tab = itTab.next();
  106. if(!(tab.getNextHop().equals(IpVecino) ||tab.getIp().equals(IpVecino))){
  107. buffer = concat ( buffer, ByteBuffer.allocate(2).put(num2).array(),ByteBuffer.allocate(2).put(num1).array(),
  108. ByteBuffer.allocate(4).put(tab.getIp().getAddress()).array(),
  109. ByteBuffer.allocate(4).put(tab.getMask().getAddress()).array(),
  110. ByteBuffer.allocate(4).put(tab.getNextHop().getAddress()).array(),
  111. ByteBuffer.allocate(4).putInt(tab.getMetrica()).array());
  112. }
  113. System.out.println(tab);
  114. }
  115. datos=new DatagramPacket (buffer,buffer.length,IpVecino,520);
  116.  
  117. cliente.send(datos);
  118. System.out.println("paquete enviado");
  119. }
  120. }catch(SocketException mes1){
  121.  
  122. }
  123.  
  124. }
  125.  
  126. //Funciona que concatena todos los arrays de bytes que se pasa para construir el paquete RIP
  127. public static byte[] concat(byte[]...arrays){
  128. // Determine the length of the result array
  129. int totalLength = 0;
  130. for (int i = 0; i < arrays.length; i++)
  131. {
  132. totalLength += arrays[i].length;
  133. }
  134.  
  135. // create the result array
  136. byte[] result = new byte[totalLength];
  137.  
  138. // copy the source arrays into the result array
  139. int currentIndex = 0;
  140. for (int i = 0; i < arrays.length; i++)
  141. {
  142. System.arraycopy(arrays[i], 0, result, currentIndex, arrays[i].length);
  143. currentIndex += arrays[i].length;
  144. }
  145.  
  146. return result;
  147. }
  148.  
  149. //FUNCION QUE SE LE PASA LA MASCARA Y TE DEVUELVE EL CIDR
  150. public static InetAddress obtenerMascara(int len) throws UnknownHostException{
  151. int mask = 0xffffffff << (32 - len);
  152. int value =mask;
  153. byte[] bytes = new byte[]{
  154. (byte)(value >>> 24), (byte)(value >> 16 & 0xff), (byte)(value >> 8 & 0xff), (byte)(value & 0xff)};
  155.  
  156. InetAddress netAddr = InetAddress.getByAddress(bytes);
  157. return netAddr;
  158. }
  159.  
  160.  
  161. //LEER PAQUETE
  162. public static void leerpaquete(DatagramPacket dp){
  163. InetAddress ipvecino = dp.getAddress();
  164.  
  165. byte[] bytes = dp.getData();
  166. int i;
  167. InetAddress ip,mascara,ssalto;
  168. byte[] buffer;
  169.  
  170. for( i=8;i<bytes.length;i+=20){
  171.  
  172. try {
  173. boolean meterTabla=false;
  174. if(bytes[i-3] !=2 && bytes[i-4] !=2)
  175. break;
  176. buffer = new byte[]{bytes[i],bytes[i+1],bytes[i+2],bytes[i+3]};
  177. ip = InetAddress.getByAddress(buffer);
  178. buffer = new byte[]{bytes[i+4],bytes[i+5],bytes[i+6],bytes[i+7]};
  179. mascara = InetAddress.getByAddress(buffer);
  180. buffer = new byte[]{bytes[i+8],bytes[i+9],bytes[i+10],bytes[i+11]};
  181. ssalto = InetAddress.getByAddress(buffer);
  182. buffer = new byte[]{bytes[i+12],bytes[i+13],bytes[i+14],bytes[i+15]};
  183. int metrica= (buffer[0]<<24) &0xff000000 | (buffer[1]<<16) &0x00ff0000 | (buffer[2]<< 8) &0x0000ff00 | (buffer[3]<< 0) &0x000000ff;
  184. tabla.get(0).setTime(System.currentTimeMillis());// Nunca se borra la priemra entrada
  185. Tabla nueva = new Tabla(ip,mascara,ssalto,metrica+1);
  186. ArrayList<Tabla> tabla2 = new ArrayList<Tabla>(tabla);
  187. Iterator<Tabla> nuevaentrada = tabla2.iterator();
  188. int contador=0;
  189. while(nuevaentrada.hasNext()){
  190. Tabla auxiliar = nuevaentrada.next();
  191. System.out.println("1"+auxiliar.getIp());
  192. System.out.println("2"+nueva.getIp());
  193. if(auxiliar.getIp().equals(nueva.getIp()) && (auxiliar.getMask().equals(nueva.getMask()))){
  194. if(auxiliar.getMetrica() == (nueva.getMetrica())){
  195. if(System.currentTimeMillis() - nueva.getTime()>90000){
  196. tabla.remove(contador);
  197. tabla.add(nueva);
  198. meterTabla=false;
  199. break;
  200. }
  201.  
  202. }
  203. else if(auxiliar.getMetrica() > (nueva.getMetrica())){
  204. tabla.remove(contador);
  205. tabla.add(nueva);
  206. meterTabla=false;
  207. break;
  208. }
  209. }else{
  210. meterTabla=true;
  211. }
  212. contador++;
  213. }
  214. if(meterTabla){
  215. tabla.add(nueva);
  216. }
  217. } catch (UnknownHostException e) {
  218. e.printStackTrace();
  219. }
  220.  
  221. }
  222.  
  223.  
  224. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement