IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)

Correction des exercices de réseau en Java

Date de publication : 26/11/2007 , Date de mise à jour : 26/11/2007

Par Humbert Florent
 

Voici la correction des exercices proposés dans le cours Réseau en Java.

I. Solutions des exercices
I-A. Exercice 1 : Obtenir l'adresse IP d'un site web
I-B. Obtenir son adresse IP
I-C. Flux bufferisés ?
I-D. Equivalent de telnet ou netcat
I-E. Serveur écoutant
I-E-1. Suite de l'exercice


I. Solutions des exercices


I-A. Exercice 1 : Obtenir l'adresse IP d'un site web


package developpez;

import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;


/**
 * @author millie
 *
 */
public class TestInetAddress {

	/**
	 * @param args
	 * @throws UnknownHostException 
	 * @throws SocketException 
	 */
	public static void main(String[] args) throws Exception {
		InetAddress address = InetAddress.getByName("www.developpez.com");
		System.out.println(address.getHostAddress());	
	}

}
 
package developpez;

import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;


/**
 * @author millie
 *
 */
public class TestInetAddress {

	/**
	 *  Permet de savoir si un hôte est valide
	 *  
	 * @param host
	 * @return true si l'adresse est valide, false sinon
	 */
	static boolean isValidAddress(String host) {
		try {
			return InetAddress.getByName(host).isReachable(100);
		}
		catch(Exception e) {
			return false;
		}
	}
	
	/**
	 * @param args
	 * @throws UnknownHostException 
	 * @throws SocketException 
	 */
	public static void main(String[] args) throws Exception {
		System.out.println(isValidAddress("www.developpez"));
	}

}

I-B. Obtenir son adresse IP

 
package developpez;

import java.io.IOException;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;

/**
 * @author millie
 * 
 */
public class TestInetAddress {

	/**
	 * @param args
	 * @throws IOException
	 * @throws UnknownHostException
	 * @throws SocketException
	 */
	public static void main(String[] args) throws IOException {
		Socket s = new Socket("www.developpez.com", 80);
		System.out.println(s.getLocalAddress().getHostAddress());
	}
}

I-C. Flux bufferisés ?


 			
package developpez;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;

/**
 * @author millie
 * 
 */
public class TestInetAddress {

	static void readAll(InputStream iStream, int bufferSize) throws IOException {
		if(bufferSize<1)
			throw new IllegalArgumentException("Taille du buffer <1");
		
		byte[] buffer = new byte[bufferSize];
	
		int total = 0;
		int bitsLus = 0;
		while (  (bitsLus = iStream.read(buffer)) > 0) {
			total+= bitsLus;
			if(total>10000)
				break;
		}
	
	}

	static void test(boolean buffered, int bufferSize) throws UnknownHostException, IOException {

		Socket s = null;
		OutputStream oStream = null;
		InputStream iStream = null;

		String g = "GET / HTTP/1.1\n" + "Host: www.yahoo.fr\n\n";

		s = new Socket("www.yahoo.fr", 80);

		// recupération des flux
		oStream = s.getOutputStream();
		iStream = s.getInputStream();

		BufferedInputStream bIStream = new BufferedInputStream(iStream, 10);

		oStream.write(g.getBytes());

		if (buffered)
			readAll(bIStream, bufferSize);
		else
			readAll(iStream, bufferSize);

		bIStream.close();
		oStream.close();
		iStream.close();
		s.close();

	}

	/**
	 * @param args
	 * @throws IOException
	 * @throws UnknownHostException
	 * @throws SocketException
	 */
	public static void main(String[] args) throws IOException {

		for(int size = 1; size<1000; size+=100)
		{
			System.out.println("Buffer de taille " + size);
			long startBuffer = System.currentTimeMillis();
			test(true, size);
			long dureeBuffer = System.currentTimeMillis() - startBuffer;
			System.out.println("BufferedInputStream Temps : " + dureeBuffer);
			
			long startSansBuffer = System.currentTimeMillis();
			test(false, size);
			long dureeSansBuffer = System.currentTimeMillis() - startSansBuffer;
			System.out.println("InputStream Temps : " + dureeSansBuffer);
			
		}
	}

}
	

I-D. Equivalent de telnet ou netcat


 			
package developpez;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * Classe dont le but est uniquement d'écouter un socket
 * 
 * @author millie
 * 
 */
class Reader extends Thread {

	private Socket socket;

	public Reader(Socket s) {
		this.socket = s;
	}

	public void run() {
		InputStream iStream = null;
		try {
			iStream = socket.getInputStream();
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					iStream)); // pour lire ligne par ligne

			String g;
			while ((g = reader.readLine()) != null) {
				System.err.println(g);
			}

		} catch (IOException e) {
			e.printStackTrace();
		}

		try {
			iStream.close(); // on ferme tout
			socket.close();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

	}
}

/**
 * @author millie
 * 
 */
public class TestInetAddress {

	/**
	 * @param args
	 * @throws IOException 
	 * @throws UnknownHostException 
	 */
	public static void main(String[] args) throws UnknownHostException, IOException {
		String host = "www.developpez.com";
		int port = 80;

		BufferedReader iReader = new BufferedReader(new InputStreamReader(
				System.in)); // pour permettre la lecture des entrées au
								// clavier

		Socket s =  new Socket(host, port);;
		OutputStream oStream = s.getOutputStream();;
		BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
				oStream));
			

		Reader reader = new Reader(s);
		reader.start(); // démarrage du thread d'écoute

		
		try {
			while (true) {
				String toSend = iReader.readLine(); // lecture d'une ligne
													// entrée au clavier
				toSend += '\n'; // ajout d'un retour à la ligne
				writer.write(toSend);
				writer.flush();
			}

		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		finally {
			s.close(); // on ferme tout
			oStream.close();
			iReader.close();
		}

	}
}
 
	

I-E. Serveur écoutant


 			
package developpez;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author millie
 * 
 */
public class TestInetAddress {

	/**
	 * @param args
	 * @throws IOException
	 * @throws UnknownHostException
	 * @throws SocketException
	 */
	public static void main(String[] args) throws IOException {
		ServerSocket server = new ServerSocket(300);
		Socket client = server.accept();
		BufferedReader reader = new BufferedReader(new InputStreamReader(client
				.getInputStream()));
		String ligne;

		try {
			while ((ligne = reader.readLine()) != null) {
				System.out.println(ligne);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			reader.close();
			client.close();
			server.close();

		}

	}

}
 
	

I-E-1. Suite de l'exercice


 	
package developpez;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

class Client extends Thread {
	private Socket client;

	Client(Socket s) {
		client = s;
	}

	public void run() {
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new InputStreamReader(client
					.getInputStream()));
			String ligne;

			while ((ligne = reader.readLine()) != null) {
				System.out.println(ligne);
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (reader != null)
					reader.close();
				if (client != null)
					client.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}

/**
 * @author millie
 * 
 */
public class TestInetAddress {

	/**
	 * @param args
	 * @throws IOException
	 * @throws UnknownHostException
	 * @throws SocketException
	 */
	public static void main(String[] args) throws IOException {
		ServerSocket server = new ServerSocket(300);

		Socket client;
		while (true) {
			client = server.accept();
			Client c = new Client(client);
			c.start();
		}

	}

}

 
	


Valid XHTML 1.0 TransitionalValid CSS!

Les sources présentées sur cette page sont libres de droits et vous pouvez les utiliser à votre convenance. Par contre, la page de présentation constitue une œuvre intellectuelle protégée par les droits d'auteur. Copyright © 2007 Florent HUMBERT. Aucune reproduction, même partielle, ne peut être faite de ce site ni de l'ensemble de son contenu : textes, documents, images, etc. sans l'autorisation expresse de l'auteur. Sinon vous encourez selon la loi jusqu'à trois ans de prison et jusqu'à 300 000 € de dommages et intérêts.