Visualizzazione dei risultati da 1 a 7 su 7

Discussione: Indirizzo ipv4 in Byte

  1. #1

    Indirizzo ipv4 in Byte

    Salve ragazzi,
    stò progettando (già ribadito per due volte ) un piccolo FireWall (questioni didattiche) in Java.
    Ho un problema con la classe InetAdress.
    Infatti avrei bisogno di creare un InetAddress identificato da un indirizzo ipv4.
    Ho compreso che debbo usare il metodo getByAddress, che ha bisogno in input di un byte[].
    Bene, ho scritto un metodo che crea l'array dalla stringa, tuttavia, ovviamente, poichè nel byte il numero massimo è 127, se metto ad esempio l'indirizzo 192.168.2.1, mi parte un eccezione:
    codice:
    Value out of range. Value:"192" Radix:10
    Dove sbaglio???

    Per semplificare vi posto il codice in una main class.

    codice:
    public class MainClass2 {
    
    	/**
    	 * @param args
    	 */
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    
    		String ipAdressString = "192.168.2.1";
    		String part1 = "";
    		String part2 = "";
    		String part3 = "";
    		String part4 = "";
    		char charByteStop = '.';
    		boolean firstPoint = false;
    		boolean secondPoint = false;
    		boolean thirdPoint = false;
    		boolean fourthPoint = false;
    		int k = 0;
    		int j = 0;
    		int h = 0;
    		int l = 0;
    		int length = ipAdressString.length() - 1;
    		if(!firstPoint && !secondPoint && !thirdPoint && !fourthPoint) {
    			for (k = 0; k <= length && k <= 3 && !firstPoint; k++) {
    				char charRead = ipAdressString.charAt(k);
    				if (charRead != charByteStop) {
    					String concString = Character.toString(charRead);
    					part1 = part1.concat(concString);
    				} else {
    					firstPoint = true;
    				}
    			}
    			for (j = k; j <= length && j <= k + 3 && firstPoint && !secondPoint; j++) {
    				char charRead = ipAdressString.charAt(j);
    				if (charRead != charByteStop) {
    					String concString = Character.toString(charRead);
    					part2 = part2.concat(concString);
    				} else {
    					secondPoint = true;
    				}
    			}
    			for (h = j; h <= length && h <= j + 3 && firstPoint && secondPoint && !thirdPoint; h++) {
    				char charRead = ipAdressString.charAt(h);
    				if (charRead != charByteStop) {
    					String concString = Character.toString(charRead);
    					part3 = part3.concat(concString);
    				} else {
    					thirdPoint = true;
    				}
    			}
    			for (l = h; l <= length && l <= h + 3 && firstPoint && secondPoint && thirdPoint && !fourthPoint; l++) {
    				char charRead = ipAdressString.charAt(l);
    				if (charRead != charByteStop) {
    					String concString = Character.toString(charRead);
    					part4 = part4.concat(concString);
    				} else {
    					fourthPoint = true;
    				}
    			}
    		}
    		Byte[] ipAdress = { new Byte(part1), new Byte(part2), new Byte(part3),
    				new Byte(part4) };
    		for (int s = 0; s <= ipAdress.length - 1; s++) {
    			System.out.print(ipAdress[h]);
    		}
    	}
    }

  2. #2
    Utente di HTML.it
    Registrato dal
    Feb 2007
    Messaggi
    4,157
    io darei un'occhiata qui e
    qui e ti ricordo che per il byte l'ottavo bit è di segno, quindi da un int potresti rappresentare valori da 0 a 255, ma essendo l'ottavo di segno, rappresenti da 0 a 127.
    In altri linguaggi avresti l'unsigned che ti viene in aiuto, qui in realtà no.

  3. #3
    Ho modificato il tutto, ora però, come controllo che il codice che mi restituisce corrisponde effettivamente all'indirizzo ip???

    codice:
    public class MainClass2 {
    
    	/**
    	 * @param args
    	 */
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    
    		String ipAdressString = "192.168.2.1";
    		int part1 = 0;
    		int part2 = 0;
    		int part3 = 0;
    		int part4 = 0;
    		char charByteStop = '.';
    		boolean firstPoint = false;
    		boolean secondPoint = false;
    		boolean thirdPoint = false;
    		boolean fourthPoint = false;
    		int k = 0;
    		int j = 0;
    		int h = 0;
    		int l = 0;
    		int length = ipAdressString.length() - 1;
    		if(!firstPoint && !secondPoint && !thirdPoint && !fourthPoint) {
    			for (k = 0; k <= length && k <= 3 && !firstPoint; k++) {
    				char charRead = ipAdressString.charAt(k);
    				if (charRead != charByteStop) {
    					part1 = (part1 * 10) + Character.getNumericValue(charRead);
    				} else {
    					firstPoint = true;
    				}
    			}
    			for (j = k; j <= length && j <= k + 3 && firstPoint && !secondPoint; j++) {
    				char charRead = ipAdressString.charAt(j);
    				if (charRead != charByteStop) {
    					part2 = (part2 * 10) + Character.getNumericValue(charRead);
    				} else {
    					secondPoint = true;
    				}
    			}
    			for (h = j; h <= length && h <= j + 3 && firstPoint && secondPoint && !thirdPoint; h++) {
    				char charRead = ipAdressString.charAt(h);
    				if (charRead != charByteStop) {
    					part3 = (part3 * 10) +Character.getNumericValue(charRead);
    				} else {
    					thirdPoint = true;
    				}
    			}
    			for (l = h; l <= length && l <= h + 3 && firstPoint && secondPoint && thirdPoint && !fourthPoint; l++) {
    				char charRead = ipAdressString.charAt(l);
    				if (charRead != charByteStop) {
    					part4 = (part4 * 10) + Character.getNumericValue(charRead);
    				} else {
    					fourthPoint = true;
    				}
    			}
    		}
    		Byte[] ipAdress = { (byte)part1, (byte)part2, (byte)part3,
    				(byte)part4 };
    		for (int s = 0; s <= ipAdress.length - 1; s++) {
    			System.out.print(ipAdress[s]);
    		}
    	}
    }

  4. #4
    Ho completato il programma e la parte riportata sopra funziona alla perfezione.
    Se qualcuno fosse interessato, la può utilizzare liberamente.
    Ricordo che serve a trasformare un indirizzo ip stringa, in un array di byte, accettato dalla classe InetAdress per il metodoInetAddress.getByAddress ( getByAddress ).
    Riporto qualche modifica e lo definisco come metodo :


    codice:
    	private byte[] setIpAdress(String ipAdressString) {
    
    		int part1 = 0;
    		int part2 = 0;
    		int part3 = 0;
    		int part4 = 0;
    		char charByteStop = '.';
    		boolean firstPoint = false;
    		boolean secondPoint = false;
    		boolean thirdPoint = false;
    		boolean fourthPoint = false;
    		int k = 0;
    		int j = 0;
    		int h = 0;
    		int l = 0;
    		int length = ipAdressString.length() - 1;
    		if (!firstPoint && !secondPoint && !thirdPoint && !fourthPoint) {
    			for (k = 0; k <= length && k <= 3 && !firstPoint; k++) {
    				char charRead = ipAdressString.charAt(k);
    				if (charRead != charByteStop) {
    					part1 = (part1 * 10) + Character.getNumericValue(charRead);
    				} else {
    					firstPoint = true;
    				}
    			}
    			for (j = k; j <= length && j <= k + 3 && firstPoint && !secondPoint; j++) {
    				char charRead = ipAdressString.charAt(j);
    				if (charRead != charByteStop) {
    					part2 = (part2 * 10) + Character.getNumericValue(charRead);
    				} else {
    					secondPoint = true;
    				}
    			}
    			for (h = j; h <= length && h <= j + 3 && firstPoint && secondPoint
    					&& !thirdPoint; h++) {
    				char charRead = ipAdressString.charAt(h);
    				if (charRead != charByteStop) {
    					part3 = (part3 * 10) + Character.getNumericValue(charRead);
    				} else {
    					thirdPoint = true;
    				}
    			}
    			for (l = h; l <= length && l <= h + 3 && firstPoint && secondPoint
    					&& thirdPoint && !fourthPoint; l++) {
    				char charRead = ipAdressString.charAt(l);
    				if (charRead != charByteStop) {
    					part4 = (part4 * 10) + Character.getNumericValue(charRead);
    				} else {
    					fourthPoint = true;
    				}
    			}
    		}
    		byte[] ipAdress = { (byte) part1, (byte) part2, (byte) part3,
    				(byte) part4 };
    		return ipAdress;
    		}
    	}

  5. #5
    Moderatore di Programmazione L'avatar di LeleFT
    Registrato dal
    Jun 2003
    Messaggi
    17,328
    Bene.
    Ora che hai risolto e hai correttamente postato la soluzione, aggiungerei qualche info.

    1) La classe InetAddress possiede il metodo statico getByName() che riceve una stringa, la quale può essere il nome di un host oppure, semplicemente, l'indirizzo IP come stringa.

    2) Nel caso si volesse, comunque, procedere alla scomposizione della stringa in un array di byte, potresti usare, semplicemente, queste quattro righe (non viene effettuato alcun controllo di coerenza sulla validità semantica del IP, basta vedere la brutalità della penultima riga, ma mi pare che non lo faccia nemmeno tu):

    codice:
    public byte[] stringIpToByteArray(String ipAddress) {
       String[] parti = ipAddress.split("\\.");
       byte[] ip = new byte[parti.length];
       for(int i=0; i<parti.length; i++) ip[i] = (byte) Integer.parseInt( parti[i] );
       return ip;
    }
    Se vogliamo aggiungere almeno il controllo sul fatto che debbano esserci 4 byte:

    codice:
    public byte[] stringIpToByteArray(String ipAddress) {
       byte[] ip = null;
       String[] parti = ipAddress.split("\\.");
       if (parti.length == 4) {
          ip = new byte[parti.length];
          for(int i=0; i<parti.length; i++) ip[i] = (byte) Integer.parseInt( parti[i] );
       }
       return ip;
    }
    Ciao.
    "Perchè spendere anche solo 5 dollari per un S.O., quando posso averne uno gratis e spendere quei 5 dollari per 5 bottiglie di birra?" [Jon "maddog" Hall]
    Fatti non foste a viver come bruti, ma per seguir virtute e canoscenza

  6. #6
    Fantastico, tutto il mio codice scomposto in 4 righe ...

    Comunque, sono stato idiota io a presupporre che getByName(), indicava solo il nome dell'host!!

  7. #7
    Moderatore di Programmazione L'avatar di LeleFT
    Registrato dal
    Jun 2003
    Messaggi
    17,328
    Originariamente inviato da generalekamikaz
    Fantastico, tutto il mio codice scomposto in 4 righe ...
    Tranquillo. Quello che hai fatto è un ottimo esercizio per imparare ad usare bene le varie classi del core Java: niente di meglio dell'esercizio per prendere mano.

    Comunque, sono stato idiota io a presupporre che getByName(), indicava solo il nome dell'host!!
    Non sarei così pessimista. Direi, piuttosto, che non hai letto tutta la documentazione del metodo.

    Dalla documentazione
    Determines the IP address of a host, given the host's name.

    The host name can either be a machine name, such as "java.sun.com", or a textual representation of its IP address. If a literal IP address is supplied, only the validity of the address format is checked.
    Non hai idea di quante volte anch'io, ritornando sulla documentazione e rileggendola per bene tutta, abbia trovato informazioni che avevo completamente trascurato... fa parte anche questa della pratica di cui sopra.


    Ciao.
    "Perchè spendere anche solo 5 dollari per un S.O., quando posso averne uno gratis e spendere quei 5 dollari per 5 bottiglie di birra?" [Jon "maddog" Hall]
    Fatti non foste a viver come bruti, ma per seguir virtute e canoscenza

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.