Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction 1-1 Protocoles réseaux Sommaire (prévision):  Introduction  Rappels programmation réseau (java)  Modèles  Systèmes de transitions, "safety.

Similar presentations


Presentation on theme: "Introduction 1-1 Protocoles réseaux Sommaire (prévision):  Introduction  Rappels programmation réseau (java)  Modèles  Systèmes de transitions, "safety."— Presentation transcript:

1 Introduction 1-1 Protocoles réseaux Sommaire (prévision):  Introduction  Rappels programmation réseau (java)  Modèles  Systèmes de transitions, "safety et liveness"  Horloges logiques, ordre causal.  Couche liaison de données  Codes correcteurs d'erreur  Couche réseau  Algorithmes de routage  Couche transport  Communication fiable  Protocole du bit alterné- sliding windows  Compléments:  Algorithmes de diffusion  Algorithmes de vagues  Broadcast et multicast  Réseaux de pairs

2 Bibliographie  Introduction to Distributed Algorithms. G. Tel. Cambridge University press.  Computer networking J.F. Kurose K.W. Ross Pearson.  Design and analysis of distributed algorithms N. Santoro Wiley-Interscience  TCP-IP Illustrated volume 1: The Protocols R. Stevens Addison-Wesley Introduction 1-2

3 Rappels: Java et internet M1 Internet et java

4 Sommaire Rappels java – Entrées-sorties – Thread Rappels tcp-udp Socket tcp et SocketServer Socket udp compléments M2 internetH. Fauconnier 4

5 Entrées-sorties java Streams – Output streams – Input streams – Filter streams – Readers et writer – (non blocking I/O) M2 internetH. Fauconnier 5

6 OuputStream public abstract class OutputStream – public abstract void write(int b) throws IOException – public void write(byte[] data) throws IOException – Public void write(byte[] data, int offset, int length) throws IOException – public void flush( ) throws IOException – public void close( ) throws IOException M2 internetH. Fauconnier 6

7 InputStream public abstract class InputStream – public abstract int read( ) throws IOException – public int read(byte[] input) throws IOException – public int read(byte[] input, int offset, int length) throws IOException – public long skip(long n) throws IOException – public int available( ) throws IOException – public void close( ) throws IOException – public void mark(int readAheadLimit) – public void reset( ) throws IOException – public boolean markSupported( ) M2 internetH. Fauconnier 7

8 Lecture: int bytesRead=0; int bytesToRead=1024; byte[] input = new byte[bytesToRead]; while (bytesRead < bytesToRead) { int result = in.read(input, bytesRead, bytesToRead - bytesRead); if (result == -1) break; bytesRead += result; } M2 internetH. Fauconnier 8

9 Filtres Chainage des filtres: DataOutputStream dout = new DataOutputStream(new BufferedOutputStream(new FileOutputStream("data.txt"))); M2 internetH. Fauconnier 9

10 Filtres Streams avec buffer – BufferedInputStream BufferedInputStream – BufferedOutputStream BufferedOutputStream PrintStream (System.out) PrintStream PushbackInputStream Streams de données (lire et écrire des données java en binaire) le codage est celui de java – DataInputStream DataInputStream – DataOutputStream DataOutputStream Streams avec compression Streams avec digest Streams cryptées M2 internetH. Fauconnier 10

11 Attention Une méthode comme println est dépendante de la plate-forme: – Le séparateur de ligne est soit \n, soit \r, soit \r\n – Le codage par défaut des caractères dépend de la plate-forme – PrintStream capte les exceptions M2 internetH. Fauconnier 11

12 Compression public class DeflaterOutputStream extends FilterOutputStreamDeflaterOutputStream public class InflaterInputStream extends FilterInputStreamInflaterInputStream public class GZIPOutputStream extends DeflaterOutputStreamGZIPOutputStream public class GZIPInputStream extends InflaterInputStreamGZIPInputStream public class ZipOutputStream extends DeflaterOutputStreamZipOutputStream public class ZipInputStream extends InflaterInputStreamZipInputStream M2 internetH. Fauconnier 12

13 décompresser une archive: FileInputStream fin = new FileInputStream("shareware.zip"); ZipInputStream zin = new ZipInputStream(fin); ZipEntry ze = null; int b = 0; while ((ze = zin.getNextEntry( )) != null) { FileOutputStream fout = new FileOutputStream(ze.getName( )); while ((b = zin.read( )) != -1) fout.write(b); zin.closeEntry( ); fout.flush( ); fout.close( ); } zin.close( ); M2 internetH. Fauconnier 13

14 Décompresser un fichier FileInputStream fin = new FileInputStream("allnames.gz"); GZIPInputStream gzin = new GZIPInputStream(fin); FileOutputStream fout = new FileOutputStream("allnames"); int b = 0; while ((b = gzin.read( )) != -1) fout.write(b); gzin.close( ); out.flush( ); out.close( ); M2 internetH. Fauconnier 14

15 digest public class DigestOutputStream extends FilterOutputStreamDigestOutputStream public class DigestInputStream extends FilterInputStreamDigestInputStream M2 internetH. Fauconnier 15

16 Digest exemple: MessageDigest sha = MessageDigest.getInstance("SHA"); DigestOutputStream dout = new DigestOutputStream(out, sha); byte[] buffer = new byte[128]; while (true) { int bytesRead = in.read(buffer); if (bytesRead < 0) break; dout.write(buffer, 0, bytesRead); } dout.flush( ); dout.close( ); byte[] result = dout.getMessageDigest( ).digest( ); M2 internetH. Fauconnier 16

17 Cryptage décryptage public CipherInputStream(InputStream in, Cipher c)CipherInputStream Cipher public CipherOutputStream(OutputStream out, Cipher c)CipherOutputStreamCipher Exemple byte[] desKeyData = "Monmotdepasse".getBytes( ); DESKeySpec desKeySpec = new DESKeySpec(desKeyData); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey desKey = keyFactory.generateSecret(desKeySpec); Cipher des = Cipher.getInstance("DES"); des.init(Cipher.DECRYPT_MODE, desKey); CipherInputStream cin = new CipherInputStream(fin, des); M2 internetH. Fauconnier 17

18 Exemple Stri ng infile = "secrets.txt"; String outfile = "secrets.des"; String password = "Un mot de passe"; try { FileInputStream fin = new FileInputStream(infile); FileOutputStream fout = new FileOutputStream(outfile); // register the provider that implements the algorithm Provider sunJce = new com.sun.crypto.provider.SunJCE( ); Security.addProvider(sunJce); char[] pbeKeyData = password.toCharArray( ); PBEKeySpec pbeKeySpec = new PBEKeySpec(pbeKeyData); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES"); SecretKey pbeKey = keyFactory.generateSecret(pbeKeySpec); M2 internetH. Fauconnier 18

19 Exemple suite // use Data Encryption Standard Cipher pbe = Cipher.getInstance("PBEWithMD5AndDES"); pbe.init(Cipher.ENCRYPT_MODE, pbeKey); CipherOutputStream cout = new CipherOutputStream(fout, pbe); byte[] input = new byte[64]; while (true) { int bytesRead = fin.read(input); if (bytesRead == -1) break; cout.write(input, 0, bytesRead); } cout.flush( ); cout.close( ); fin.close( ); } catch (Exception ex) { System.err.println(ex); } M2 internetH. Fauconnier 19

20 Readers et Writers Hiérarchie de classe pour les caractères (avec encodage) au lieu d’octets. Writer et Reader classes abstraites WriterReader – OutputStreamWriter OutputStreamWrite – InputStreamReader InputStreamReader – Filtres BufferedReader, BufferedWriter LineNumberReader PushbackReader PrintReader M2 internetH. Fauconnier 20

21 Reader et Writer OutputStreamWriter reçoit des caractères, les convertit en octets suivant un certain codage public OutputStreamWriter(OutputStream out, String encoding) throws UnsupportedEncodingException public OutputStreamWriter(OutputStream out) Exemple: OutputStreamWriter w = new OutputStreamWriter(new FileOutputStream(russe.txt,"Cp1251")); M2 internetH. Fauconnier 21

22 Reader et Writer InputStreamReader lit des octets et les convertit suivant un certain codage – public InputStreamReader(InputStream in) – public InputStreamReader(InputStream in, String encoding) throws UnsupportedEncodingException public static String getMacCyrillicString(InputStream in) throws IOException { InputStreamReader r = new InputStreamReader(in, "MacCyrillic"); StringBuffer sb = new StringBuffer( ); int c; while ((c = r.read( )) != -1) sb.append((char) c); r.close( ); return sb.toString( ); } M2 internetH. Fauconnier 22

23 Filtres BufferedReader BufferedWriter LineNumberReader PushbackReader PrintWriter M2 internetH. Fauconnier 23

24 Threads M2 internetH. Fauconnier 24

25 Threads threads: plusieurs activités qui coexistent et partagent des données – exemples: pendant un chargement long faire autre chose coopérer processus versus threads – problème de l'accès aux ressources partagées verrous moniteur synchronisation threadPOO-L3 H. Fauconnier 25

26 Principes de base extension de la classe Thread – méthode run est le code qui sera exécuté. – la création d'un objet dont la superclasse est Thread crée la thread (mais ne la démarre pas) – la méthode start démarre la thread (et retourne immédiatement) – la méthode join permet d'attendre la fin de la thread – les exécutions des threads sont asynchrones et concurrentes threadPOO-L3 H. Fauconnier 26

27 Exemple class ThreadAffiche extends Thread{ private String mot; private int delay; public ThreadAffiche(String w,int duree){ mot=w; delay=duree; } public void run(){ try{ for(;;){ System.out.println(mot); Thread.sleep(delay); } }catch(InterruptedException e){ } threadPOO-L3 H. Fauconnier 27

28 Suite public static void main(String[] args) { new ThreadAffiche("PING", 10).start(); new ThreadAffiche("PONG", 30).start(); new ThreadAffiche("Splash!",60).start(); } threadPOO-L3 H. Fauconnier 28

29 Alternative: Runnable Une autre solution: – créer une classe qui implémente l'interface Runnable (cette interface contient la méthode run ) – créer une Thread à partir du constructeur Thread avec un Runnable comme argument. threadPOO-L3 H. Fauconnier 29

30 Exemple class RunnableAffiche implements Runnable{ private String mot; private int delay; public RunnableAffiche(String w,int duree){ mot=w; delay=duree; } public void run(){ try{ for(;;){ System.out.println(mot); Thread.sleep(delay); } }catch(InterruptedException e){ } threadPOO-L3 H. Fauconnier 30

31 Suite public static void main(String[] args) { Runnable ping=new RunnableAffiche("PING", 10); Runnable pong=new RunnableAffiche("PONG", 50); new Thread(ping).start(); new Thread(pong).start(); } threadPOO-L3 H. Fauconnier 31

32 Synchronisation les threads s'exécutent concurremment et peuvent accéder concurremment à des objets: – il faut contrôler l'accès: – thread un lit une variable (R1) puis modifie cette variable (W1) – thread deux lit la même variable (R2) puis la modifie (W2) – R1-R2-W2-W1 – R1-W1-R2-W2 résultat différent! threadPOO-L3 H. Fauconnier 32

33 Exemple class X{ int val; } class Concur extends Thread{ X x; int i; String nom; public Concur(String st, X x){ nom=st; this.x=x; } public void run(){ i=x.val; System.out.println("thread:"+nom+" valeur x="+i); try{ Thread.sleep(10); }catch(Exception e){} x.val=i+1; System.out.println("thread:"+nom+" valeur x="+x.val); } threadPOO-L3 H. Fauconnier 33

34 Suite public static void main(String[] args) { X x=new X(); Thread un=new Concur("un",x); Thread deux=new Concur("deux",x); un.start(); deux.start(); try{ un.join(); deux.join(); }catch (InterruptedException e){} System.out.println("X="+x.val); } donnera (par exemple) thread:un valeur x=0 thread:deux valeur x=0 thread:un valeur x=1 thread:deux valeur x=1 X=1 threadPOO-L3 H. Fauconnier 34

35 Deuxième exemple class Y{ int val=0; public int increment(){ int tmp=val; tmp++; try{ Thread.currentThread().sleep(100); }catch(Exception e){} val=tmp; return(tmp); } int getVal(){return val;} } class Concur1 extends Thread{ Y y; String nom; public Concur1(String st, Y y){ nom=st; this.y=y; } public void run(){ System.out.println("thread:"+nom+" valeur="+y.increment()); } threadPOO-L3 H. Fauconnier 35

36 Suite public static void main(String[] args) { Y y=new Y(); Thread un=new Concur1("un",y); Thread deux=new Concur1("deux",y); un.start(); deux.start(); try{ un.join(); deux.join(); }catch (InterruptedException e){} System.out.println("Y="+y.getVal()); } thread:un valeur=1 thread:deux valeur=1 Y=1 threadPOO-L3 H. Fauconnier 36

37 Verrous à chaque objet est associé un verrou – synchronized(expr) {instructions} expr doit s'évaluer comme une référence à un objet verrou sur cet objet pour la durée de l'exécution de instructions – déclarer les méthodes comme synchronized: la thread obtient le verrou et le relâche quand la méthode se termine threadPOO-L3 H. Fauconnier 37

38 synchronised(x) class Concur extends Thread{ X x; int i; String nom; public Concur(String st, X x){ nom=st; this.x=x; } public void run(){ synchronized(x){ i=x.val; System.out.println("thread:"+nom+" valeur x="+i); try{ Thread.sleep(10); }catch(Exception e){} x.val=i+1; System.out.println("thread:"+nom+" valeur x="+x.val); } threadPOO-L3 H. Fauconnier 38

39 Méthode synchronisée class Y{ int val=0; public synchronized int increment(){ int tmp=val; tmp++; try{ Thread.currentThread().sleep(100); }catch(Exception e){} val=tmp; return(tmp); } int getVal(){return val;} } thread:un valeur=1 thread:deux valeur=2 Y=2 threadPOO-L3 H. Fauconnier 39

40 Mais… la synchronisation par des verrous peut entraîner un blocage: – la thread un (XA) pose un verrou sur l'objet A et (YB) demande un verrou sur l'objet B – la thread deux (XB) pose un verrou sur l'objet B et (YA) demande un verrou sur l'objet A – si XA –XB : ni YA ni YB ne peuvent être satisfaites -> blocage (pour une méthode synchronisée, le verrou concerne l'objet globalement et pas seulement la méthode) threadPOO-L3 H. Fauconnier 40

41 Exemple class Dead{ Dead partenaire; String nom; public Dead(String st){ nom=st; } public synchronized void f(){ try{ Thread.currentThread().sleep(100); }catch(Exception e){} System.out.println(Thread.currentThread().getName()+ " de "+ nom+".f() invoque "+ partenaire.nom+".g()"); partenaire.g(); } public synchronized void g(){ System.out.println(Thread.currentThread().getName()+ " de "+ nom+".g()"); } public void setPartenaire(Dead d){ partenaire=d; } threadPOO-L3 H. Fauconnier 41

42 Exemple (suite) final Dead un=new Dead("un"); final Dead deux= new Dead("deux"); un.setPartenaire(deux); deux.setPartenaire(un); new Thread(new Runnable(){public void run(){un.f();} },"T1").start(); new Thread(new Runnable(){public void run(){deux.f();} },"T2").start(); T1 de un.f() invoque deux.g() T2 de deux.f() invoque un.g() threadPOO-L3 H. Fauconnier 42

43 Synchronisation… wait, notifyAll notify – attendre une condition / notifier le changement de condition: synchronized void fairesurcondition(){ while(!condition) wait(); faire ce qu'il faut qaund la condition est vraie } synchronized void changercondition(){ … changer quelque chose concernant la condition notifyAll(); // ou notify() } threadPOO-L3 H. Fauconnier 43

44 Exemple: public class Cellule { private Cellule suivant; private E element; public Cellule(E val) { this.element=val; } public Cellule(E val, Cellule suivant){ this.element=val; this.suivant=suivant; } public E getElement(){ return element; } public void setElement(E v){ element=v; } public Cellule getSuivant(){ return suivant; } public void setSuivant(Cellule s){ this.suivant=s; } threadPOO-L3 H. Fauconnier 44

45 Files synchronisées class File { protected Cellule tete, queue; private int taille=0; public synchronized void enfiler(E item){ Cellule c=new Cellule (item); if (queue==null) tete=c; else{ queue.setSuivant(c); } c.setSuivant(null); queue = c; notifyAll(); } threadPOO-L3 H. Fauconnier 45

46 File (suite) public synchronized E defiler() throws InterruptedException{ while (tete == null) wait(); Cellule tmp=tete; tete=tete.getSuivant(); if (tete == null) queue=null; return tmp.getElement(); } threadPOO-L3 H. Fauconnier 46

47 Réseau et Java Rappels Tcp-udp M2 internetH. Fauconnier 47

48 I) Introduction Les couches M2 internetH. Fauconnier 48

49 Couche Internet Datagramme IPv4 M2 internetH. Fauconnier 49

50 Couche transport TCP – Mode connecté, flot bidirectionnel, sûr, contrôle de la congestion – Téléphone UDP – Mode non connecté, messages, sans garantie, déséquencement – Poste M2 internetH. Fauconnier 50

51 Adresses internet Adresse IP: adresse réseau + site sur le réseau Exemple: M2 internetH. Fauconnier 51

52 Classe d’adresses Internet ClasseBits départDébutFinNotation CIDRMasque ss-réseau Classe A / Classe B / Classe C / Classe D (mcast) /4non défini Classe E (réservée) /4non défini M2 internetH. Fauconnier 52 ClasseNombre de réseaux possiblesNombre d'ordinateurs maxi sur chacun A B C

53 Connexion Adresse IP +port Ports réservés Ports libres M2 internetH. Fauconnier 53

54 Quelques ports M2 internetH. Fauconnier 54 ProtocolPortProtocol echo7TCP/UDP discard9TCP/UDP daytime13TCP/UDP FTP data20TCP FTP21TCP SSH22TCP telnet23TCP smtp25TCP time37TCP/UDP ProtocolPortProtocol whois43TCP finger79TCP HTTP80TCP POP3110TCP NNTP119TCP IMAP143TCP RMI Registry TCP

55 Proxys M2 internetH. Fauconnier 55

56 Client-serveur M2 internetH. Fauconnier 56

57 Classes java.net.InetAddress (implements java.io.Serializable)InetAddressSerializable – java.net.Inet4AddressInet4Address – java.net.Inet6AddressInet6Address java.net.DatagramPacketDatagramPacket java.net.DatagramSocketDatagramSocket – java.net.MulticastSocketMulticastSocket java.net.ServerSocketServerSocket javax.net.ssl.SSLServerSocketSSLServerSocket java.net.SocketSocket – javax.net.ssl.SSLSocketSSLSocket java.net.SocketAddress (implements java.io.Serializable)SocketAddressSerializable – java.net.InetSocketAddressInetSocketAddress M2 internetH. Fauconnier 57

58 II) Adresses internet Classe InetAddress : Ontenir une InetAddress: – En utilisant le DNS public static InetAddress getByName(String hostName) throws UnknownHostException public static InetAddress[] getAllByName(String hostName) throws UnknownHostException public static InetAddress getLocalHost( ) throws UnknownHostException – Sans DNS public static InetAddress getByAddress(byte[] address) throws UnknownHostException public static InetAddress getByAddress(String hostName, byte[] address) throws UnknownHostException M2 internetH. Fauconnier 58

59 Exemples import java.net.*; /... public static void main (String[] args){ try { InetAddress adresse = InetAddress.getByName("liafa.jussieu.fr"); System.out.println(adresse); } catch (UnknownHostException ex) { System.out.println("liafa.jussieu.fr ??"); } M2 internetH. Fauconnier 59

60 Exemples public static void main (String[] args){ try { InetAddress ad = InetAddress.getByName(" "); System.out.println(ad); } catch (UnknownHostException ex) { System.out.println(" ??"); } M2 internetH. Fauconnier 60

61 Toutes les adresses… public static void AllAdresses(String st) { try { InetAddress[] addresses = InetAddress.getAllByName(st); for (int i = 0; i < addresses.length; i++) { System.out.println(addresses[i]); } } catch (UnknownHostException ex) { System.out.println(st+"est inconnu"); } M2 internetH. Fauconnier 61

62 Mon adresse public static String MonAdresse() { try { InetAddress moi = InetAddress.getLocalHost(); return( moi.getHostAddress()); } catch (UnknownHostException ex) { return("Mon adresse est inconnue"); } } M2 internetH. Fauconnier 62

63 InetAddress méthodes… public String getHostName( ) public byte[] getAddress( ) public String getHostAddress( ) Exemple: public static void main (String[] args) { try { InetAddress ia= InetAddress.getByName(" "); System.out.println(ia.getHostName( )); } catch (Exception ex) { System.err.println(ex); } } M2 internetH. Fauconnier 63

64 Divers… public boolean isAnyLocalAddress( ) « wildcard »? public boolean isLoopbackAddress( ) public boolean isMulticastAddress( ) Java 1.5 – public boolean isReachable(int timeout) throws IOException – public boolean isReachable(NetworkInterface interface, int ttl, int timeout) throws IOException – IPV4 et IPV6: public final class Inet4Address extends InetAddress public final class Inet6Address extends InetAddress M2 internetH. Fauconnier 64

65 NetworkInterface Exemple: try { NetworkInterface ni = NetworkInterface.getByName("eth0"); if (ni == null) { System.err.println(" pas de: eth0" ); } } catch (SocketException ex) { } M2 internetH. Fauconnier 65

66 Exemple public static String lookup(String host) { InetAddress node; // récupérer l'adresse par getByName try { node = InetAddress.getByName(host); } catch (UnknownHostException ex) { return "hôte inconnu " + host; } if (isHostname(host)) { return node.getHostAddress(); } else { return node.getHostName(); } M2 internetH. Fauconnier 66

67 sockets (client)

68 Généralités Une connexion: – (IP adresse+port, IP adresse +port) – On peut lire et écrire sur la socket Serveur: – Associer une socket à une adresse connue (IP+port) – Ecoute sur la socket – Quand une connexion arrive accept : une nouvelle socket est créée Rendre le service envoyer/recevoir – (en général dans une thread) Continuer à écouter Client: – Crée une socket – Demande connexion sur adresse +port du serveur – Connexion – Envoyer/recevoir – Fin de la connexion M2 internetH. Fauconnier 68

69 Socket en Java Serveur – Classe ServerSocket (bind (mais en général par constructeur) listen) Accept getInputStream, getOutputStream close Client – Classe Socket (bind) connect (mais en général par constructeur) getInputStream, getOutputStream close M2 internetH. Fauconnier 69

70 Attention! L’accès aux ports est souvent restreint Des firewall peuvent empêcher les connexions Il faut être root pour utiliser des ports réservés… M2 internetH. Fauconnier 70

71 Côté client Création: public Socket(InetAddress address, int port) throws IOExceptionInetAddressIOException Crée une socket + une connexion avec IP adresse et port – En fait: Création d’une socket locale attachée à un port + une adresse locale Etablissement de la connexion IOException en cas d’échec M2 internetH. Fauconnier 71

72 Exemple public static void regarderPortBas(String host) { for (int i = 1; i < 1024; i++) { try { Socket s = new Socket(host, i); System.out.println("Il y a un serveur sur " + i + " de "+ host); } catch (UnknownHostException ex) { System.err.println(ex); break; } catch (IOException ex) { // exception s'il n'y a pas de serveur } M2 internetH. Fauconnier 72

73 Attention Cet exemple peut ne pas bien fonctionner… – Pour des raisons de sécurité la tentative de connexion peut être bloquante M2 internetH. Fauconnier 73

74 Obtenir des infos… public InetAddress getInetAddress( ) public int getPort( ) public InetAddress getLocalAddress( ) public int getLocalPort( ) M2 internetH. Fauconnier 74

75 Exemple public static void socketInfo(String... args) { for (int i = 0; i < args.length; i++) { try { Socket theSocket = new Socket(args[i], 80); System.out.println("Connecté sur " + theSocket.getInetAddress() + " port " + theSocket.getPort() + " depuis port " + theSocket.getLocalPort() + " de " + theSocket.getLocalAddress()); } catch (UnknownHostException ex) { System.err.println("Hôte inconnu " + args[i]); } catch (SocketException ex) { System.err.println("Connection impossible " + args[i]); } catch (IOException ex) { System.err.println(ex); } M2 internetH. Fauconnier 75

76 Communiquer… public InputStream getInputStream( ) throws IOException public OutputStream getOutputStream( ) throws IOException M2 internetH. Fauconnier 76

77 Exemple: dayTime public static void time(String... hlist) { for (int i=0;i

78 Exemple: echo public static void echo(String hostname, int port) { PrintWriter out = null; BufferedReader networkIn = null; try { Socket theSocket = new Socket(hostname, port); networkIn = new BufferedReader( new InputStreamReader(theSocket.getInputStream())); BufferedReader userIn = new BufferedReader( new InputStreamReader(System.in)); out = new PrintWriter(theSocket.getOutputStream()); System.out.println("Client: Connecté au serveur d'echo "+ theSocket); while (true) { String theLine = userIn.readLine(); out.println(theLine); out.flush(); if (theLine.equals(".")){out.close(); break;} System.out.println(networkIn.readLine()); } catch (IOException ex) {System.err.println(ex); } finally { try { if (networkIn != null) networkIn.close(); if (out != null) out.close(); } catch (IOException ex) {} } M2 internetH. Fauconnier 78

79 Echo suite catch (IOException ex) { System.err.println(ex); } finally { try { if (networkIn != null) networkIn.close(); if (out != null) out.close(); } catch (IOException ex) {} } M2 internetH. Fauconnier 79

80 Fermeture public void close( ) throws IOException Fermeture de la socket: – Automatique si une des parties fait un close – garbage collector – (le réseau utilise des ressources systèmes qui sont par définition partagées et limitées) – (a priori à mettre dans une clause finally ) M2 internetH. Fauconnier 80

81 En plus public boolean isClosed( ) public boolean isConnected( ) public boolean isBound( ) public void shutdownInput( ) throws IOException public void shutdownOutput( ) throws IOException M2 internetH. Fauconnier 81

82 ServerSocket

83 Principe 1.Création d’un ServerSocket par constructeur 2.Association (bind) de la socket à une adresse et un port ((1) et (2) peuvent être simultanés) 3.Écoute et connexion par accept 1.Communication getInputStream et getOutputStream 2.close (par le client ou le serveur ou les deux) 4.Aller en (2) (en général 3 est dans une thread) M2 internetH. Fauconnier 83

84 Constructeurs – public ServerSocket(int port) throws BindException, IOException – public ServerSocket(int port, int queueLength) throws BindException, IOException – public ServerSocket(int port, int queueLength, InetAddress bindAddress) throws IOException Ces constructeurs associent un port et une adresse au ServerSocket l’usage du port est exclusif et si le port est déjà occupé une exception est lancée ServerSocket – public ServerSocket( ) throws IOException M2 internetH. Fauconnier 84

85 Exemple public static void portsLibres() { for (int port = 1; port <= 65535; port++) { try { // exception si le port est utilisé ServerSocket server = new ServerSocket(port); } catch (IOException ex) { System.out.println("serveur sur port" + port ); } M2 internetH. Fauconnier 85

86 Remarques port 0: choisi par le système on peut donner une taille sur la file des connexions en attente on peut choisir une adresse particulière sur la machine locale En java >1.4 on peut faire un "bind" explicite: public void bind(SocketAddress endpoint) throws IOException public void bind(SocketAddress endpoint, int queueLength) throws IOException M2 internetH. Fauconnier 86

87 Exemple public static void portQuelconque() { try { ServerSocket server = new ServerSocket(0); System.out.println("Le port obtenu est " + server.getLocalPort()); } catch (IOException ex) { System.err.println(ex); } M2 internetH. Fauconnier 87

88 Connexion accept() crée et retourne une nouvelle socket pour la connexion associée (IP, port)(IP, port) M2 internetH. Fauconnier 88

89 Exemple ServerSocket server = new ServerSocket(5776); while (true) { Socket connection = server.accept( ); OutputStreamWriter out = new OutputStreamWriter( connection.getOutputStream( )); out.write("Connecté:" +connection+"\r\n"); connection.close( ); } M2 internetH. Fauconnier 89

90 Exemple plus complet public final static int DEFAULT_PORT = 13; public static void dayTime(){ dayTime(DEFAULT_PORT); } public static void dayTime(int port) { if (port = 65536) { System.out.println("Erreur port:"); return; } try { ServerSocket server = new ServerSocket(port); Socket connection = null; M2 internetH. Fauconnier 90

91 Exemple suite while (true) { try { connection = server.accept(); Writer out = new OutputStreamWriter( connection.getOutputStream()); Date now = new Date(); out.write(now.toString() +"\r\n"); out.flush(); connection.close(); } catch (IOException ex) {} finally { try { if (connection != null) connection.close(); } catch (IOException ex) {} } } catch (IOException ex) { System.err.println(ex); } M2 internetH. Fauconnier 91

92 Fermeture public void close( ) throws IOException Ferme le ServerSocket et toutes les connexions créées par accept sur la ServerSocket M2 internetH. Fauconnier 92

93 Serveur echo public static void serveurEcho(int port) { try { ServerSocket server = new ServerSocket(port,100); System.out.println("Serveur:"+server+" en écoute sur le port: " + server.getLocalPort()+" est lancé"); while (true) { Socket connection = server.accept(); System.out.println("Serveur connexion avec: " + connection); Thread echo=new EchoThread(connection); echo.start(); } catch (IOException ex) { System.out.println("le port" + port + " est occupé"); System.out.println("On suppose donc que le service estlancé"); } } M2 internetH. Fauconnier 93

94 serveur echo: EchoThread class EchoThread extends Thread { BufferedReader in; PrintWriter out; Socket connection; public EchoThread(Socket connection) { try{ this.connection=connection; InputStream in=connection.getInputStream(); OutputStream out=connection.getOutputStream(); this.in = new BufferedReader(new InputStreamReader(in)); this.out = new PrintWriter(out); } catch (IOException ex) { System.err.println(ex); } M2 internetH. Fauconnier 94

95 run public void run() { try { while (true) { String st; st = in.readLine(); if (st.equals(".")) in.close(); out.close(); break; } System.out.println("Serveur a reçu:"+st+" de "+connection); out.println(st); out.flush(); } } catch (SocketException ex) { ex.printStackTrace(); } catch (IOException ex) { System.err.println(ex); } try { in.close(); out.close(); } catch (IOException ex) { ex.printStackTrace();} } M2 internetH. Fauconnier 95

96 Remarques utilisation des threads pour traiter le service et éviter de faire attendre les clients on peut aussi utiliser des entrées/sorties non bloquantes M2 internetH. Fauconnier 96

97 Autres méthodes public InetAddress getInetAddress( ) public int getLocalPort( ) M2 internetH. Fauconnier 97

98 Socket UDP H. Fauconnier 1-98 M2-Internet Java

99 UDP H. Fauconnier M2-Internet Java 99

100 M2-Internet Java 100 Socket programming with UDP UDP: no “connection” between client and server  no handshaking  sender explicitly attaches IP address and port of destination to each segment  OS attaches IP address and port of sending socket to each segment  Server can extract IP address, port of sender from received segment application viewpoint UDP provides unreliable transfer of groups of bytes (“datagrams”) between client and server Note: the official terminology for a UDP packet is “datagram”. In this class, we instead use “UDP segment”. H. Fauconnier

101 Running example  Client:  User types line of text  Client program sends line to server  Server:  Server receives line of text  Capitalizes all the letters  Sends modified line to client  Client:  Receives line of text  Displays M2-Internet Java 101 H. Fauconnier

102 M2-Internet Java 102 Client/server socket interaction: UDP Server (running on hostid ) close clientSocket read datagram from clientSocket create socket, clientSocket = DatagramSocket() Client Create datagram with server IP and port=x; send datagram via clientSocket create socket, port= x. serverSocket = DatagramSocket() read datagram from serverSocket write reply to serverSocket specifying client address, port number H. Fauconnier

103 M2-Internet Java 103 Example: Java client (UDP) Output: sends packet (recall that TCP sent “byte stream”) Input: receives packet (recall thatTCP received “byte stream”) Client process client UDP socket H. Fauconnier

104 M2-Internet Java 104 Example: Java client (UDP) import java.io.*; import java.net.*; class UDPClient { public static void main(String args[]) throws Exception { BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in)); DatagramSocket clientSocket = new DatagramSocket(); InetAddress IPAddress = InetAddress.getByName("hostname"); byte[] sendData = new byte[1024]; byte[] receiveData = new byte[1024]; String sentence = inFromUser.readLine(); sendData = sentence.getBytes(); Create input stream Create client socket Translate hostname to IP address using DNS H. Fauconnier

105 M2-Internet Java 105 Example: Java client (UDP), cont. DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876); clientSocket.send(sendPacket); DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); clientSocket.receive(receivePacket); String modifiedSentence = new String(receivePacket.getData()); System.out.println("FROM SERVER:" + modifiedSentence); clientSocket.close(); } Create datagram with data-to-send, length, IP addr, port Send datagram to server Read datagram from server H. Fauconnier

106 M2-Internet Java 106 Example: Java server (UDP) import java.io.*; import java.net.*; class UDPServer { public static void main(String args[]) throws Exception { DatagramSocket serverSocket = new DatagramSocket(9876); byte[] receiveData = new byte[1024]; byte[] sendData = new byte[1024]; while(true) { DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); serverSocket.receive(receivePacket); Create datagram socket at port 9876 Create space for received datagram Receive datagram H. Fauconnier

107 M2-Internet Java 107 Example: Java server (UDP), cont String sentence = new String(receivePacket.getData()); InetAddress IPAddress = receivePacket.getAddress(); int port = receivePacket.getPort(); String capitalizedSentence = sentence.toUpperCase(); sendData = capitalizedSentence.getBytes(); DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port); serverSocket.send(sendPacket); } Get IP addr port #, of sender Write out datagram to socket End of while loop, loop back and wait for another datagram Create datagram to send to client H. Fauconnier

108 UDP observations & questions  Both client server use DatagramSocket  Dest IP and port are explicitly attached to segment.  What would happen if change both clientSocket and serverSocket to “mySocket”?  Can the client send a segment to server without knowing the server’s IP address and/or port number?  Can multiple clients use the server? M2-Internet Java 108 H. Fauconnier

109 DatagramPacket  Un paquet contient au plus 65,507 bytes  Pour construire les paquet  public DatagramPacket(byte[] buffer, int length)  public DatagramPacket(byte[] buffer, int offset, int length)  Pour construire et envoyer  public DatagramPacket(byte[] data, int length, InetAddress destination, int port)  public DatagramPacket(byte[] data, int offset, int length, InetAddress destination, int port)  public DatagramPacket(byte[] data, int length, SocketAddress destination, int port)  public DatagramPacket(byte[] data, int offset, int length, SocketAddress destination, int port) H. Fauconnier M2-Internet Java 109

110 Exemple String s = "On essaie…"; byte[] data = s.getBytes("ASCII"); try { InetAddress ia = InetAddress.getByName("www.liafa.jussieu.fr "); int port = 7;// existe-t-il? DatagramPacket dp = new DatagramPacket(data, data.length, ia, port); } catch (IOException ex) } H. Fauconnier M2-Internet Java 110

112 Méthodes (suite)  Manipulation des données:  public byte[] getData( )  public int getLength( )  public int getOffset( )  public void setData(byte[] data)  public void setData(byte[] data, int offset, int length )  public void setLength(int length) H. Fauconnier M2-Internet Java 112

113 Exemple import java.net.*; public class DatagramExample { public static void main(String[] args) { String s = "Essayons."; byte[] data = s.getBytes( ); try { InetAddress ia = InetAddress.getByName("www.liafa.jussieu.fr"); int port =7; DatagramPacket dp = new DatagramPacket(data, data.length, ia, port); System.out.println(" Un packet pour" + dp.getAddress( ) + " port " + dp.getPort( )); System.out.println("il y a " + dp.getLength( ) + " bytes dans le packet"); System.out.println( new String(dp.getData( ), dp.getOffset( ), dp.getLength( ))); } catch (UnknownHostException e) { System.err.println(e); } H. Fauconnier M2-Internet Java 113

114 DatagramSocket  Constructeurs  public DatagramSocket( ) throws SocketException  public DatagramSocket(int port) throws SocketException  public DatagramSocket(int port, InetAddress interface) throws SocketException  public DatagramSocket(SocketAddress interface) throws SocketException  (protected DatagramSocket(DatagramSocketImpl impl) throws SocketException) H. Fauconnier M2-Internet Java 114

115 Exemple java.net.*; public class UDPPortScanner { public static void main(String[] args) { for (int port = 1024; port <= 65535; port++) { try { // exception si utilisé DatagramSocket server = new DatagramSocket(port); server.close( ); } catch (SocketException ex) { System.out.println("Port occupé" + port + "."); } // end try } // end for } H. Fauconnier M2-Internet Java 115

116 Envoyer et recevoir  public void send(DatagramPacket dp) throws IOException  public void receive(DatagramPacket dp) throws IOException H. Fauconnier M2-Internet Java 116

117 Un exemple: Echo  UDPServeur  UDPEchoServeur  UDPEchoClient SenderThread ReceiverThread H. Fauconnier M2-Internet Java 117

118 Echo: UDPServeur import java.net.*; import java.io.*; public abstract class UDPServeur extends Thread { private int bufferSize; protected DatagramSocket sock; public UDPServeur(int port, int bufferSize) throws SocketException { this.bufferSize = bufferSize; this.sock = new DatagramSocket(port); } public UDPServeur(int port) throws SocketException { this(port, 8192); } public void run() { byte[] buffer = new byte[bufferSize]; while (true) { DatagramPacket incoming = new DatagramPacket(buffer, buffer.length); try { sock.receive(incoming); this.respond(incoming); } catch (IOException e) { System.err.println(e); } } // end while } public abstract void respond(DatagramPacket request); } H. Fauconnier M2-Internet Java 118

119 UDPEchoServeur public class UDPEchoServeur extends UDPServeur { public final static int DEFAULT_PORT = 2222; public UDPEchoServeur() throws SocketException { super(DEFAULT_PORT); } public void respond(DatagramPacket packet) { try { byte[] data = new byte[packet.getLength()]; System.arraycopy(packet.getData(), 0, data, 0, packet.getLength()); try { String s = new String(data, "8859_1"); System.out.println(packet.getAddress() + " port " + packet.getPort() + " reçu " + s); } catch (java.io.UnsupportedEncodingException ex) {} DatagramPacket outgoing = new DatagramPacket(packet.getData(), packet.getLength(), packet.getAddress(), packet.getPort()); sock.send(outgoing); } catch (IOException ex) { System.err.println(ex); } H. Fauconnier M2-Internet Java 119

120 Client: UDPEchoClient public class UDPEchoClient { public static void lancer(String hostname, int port) { try { InetAddress ia = InetAddress.getByName(hostname); SenderThread sender = new SenderThread(ia, port); sender.start(); Thread receiver = new ReceiverThread(sender.getSocket()); receiver.start(); } catch (UnknownHostException ex) { System.err.println(ex); } catch (SocketException ex) { System.err.println(ex); } } // end lancer } H. Fauconnier M2-Internet Java 120

121 ReceiverThread class ReceiverThread extends Thread { DatagramSocket socket; private boolean stopped = false; public ReceiverThread(DatagramSocket ds) throws SocketException { this.socket = ds; } public void halt() { this.stopped = true; } public DatagramSocket getSocket(){ return socket; } public void run() { byte[] buffer = new byte[65507]; while (true) { if (stopped) return; DatagramPacket dp = new DatagramPacket(buffer, buffer.length); try { socket.receive(dp); String s = new String(dp.getData(), 0, dp.getLength()); System.out.println(s); Thread.yield(); } catch (IOException ex) {System.err.println(ex); } } H. Fauconnier M2-Internet Java 121

122 SenderThread public class SenderThread extends Thread { private InetAddress server; private DatagramSocket socket; private boolean stopped = false; private int port; public SenderThread(InetAddress address, int port) throws SocketException { this.server = address; this.port = port; this.socket = new DatagramSocket(); this.socket.connect(server, port); } public void halt() { this.stopped = true; } //… H. Fauconnier M2-Internet Java 122

123 SenderThread //… public DatagramSocket getSocket() { return this.socket; } public void run() { try { BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in)); while (true) { if (stopped) return; String theLine = userInput.readLine(); if (theLine.equals(".")) break; byte[] data = theLine.getBytes(); DatagramPacket output = new DatagramPacket(data, data.length, server, port); socket.send(output); Thread.yield(); } } // end try catch (IOException ex) {System.err.println(ex); } } // end run } H. Fauconnier M2-Internet Java 123

124 Autres méthodes  public void close( )  public int getLocalPort( )  public InetAddress getLocalAddress( )  public SocketAddress getLocalSocketAddress( )  public void connect(InetAddress host, int port)  public void disconnect( )  public int getPort( )  public InetAddress getInetAddress( )  public InetAddress getRemoteSocketAddress( ) H. Fauconnier M2-Internet Java 124

125 Options  SO_TIMEOUT  public synchronized void setSoTimeout(int timeout) throws SocketException  public synchronized int getSoTimeout( ) throws IOException  SO_RCVBUF  public void setReceiveBufferSize(int size) throws SocketException  public int getReceiveBufferSize( ) throws SocketException  SO_SNDBUF  public void setSendBufferSize(int size) throws SocketException  int getSendBufferSize( ) throws SocketException  SO_REUSEADDR (plusieurs sockets sur la même adresse)  public void setReuseAddress(boolean on) throws SocketException  boolean getReuseAddress( ) throws SocketException  SO_BROADCAST  public void setBroadcast(boolean on) throws SocketException  public boolean getBroadcast( ) throws SocketException H. Fauconnier M2-Internet Java 125

126 Introduction Chapitre 1 Introduction  Les transparents sont adaptés de (et en anglais): Computer Networking: A Top Down Approach Featuring the Internet J.F Kurose and K.W. Ross

127 Introduction Chapter 1: Introduction Our goal:  get “feel” and terminology  more depth, detail later in course  approach:  use Internet as example Overview:  what’s the Internet?  what’s a protocol?  network edge; hosts, access net, physical media  network core: packet/circuit switching, Internet structure  performance: loss, delay, throughput  security  protocol layers, service models  history

128 Introduction Chapitre 1: sommaire 1.1 What is the Internet? 1.2 Network edge  end systems, access networks, links 1.3 Network core  circuit switching, packet switching, network structure 1.4 Delay, loss and throughput in packet-switched networks 1.5 Protocol layers, service models 1.6 Networks under attack: security 1.7 History

129 Introduction What’s the Internet:  millions of connected computing devices: hosts = end systems  running network apps Home network Institutional network Mobile network Global ISP Regional ISP router PC server wireless laptop cellular handheld wired links access points  communication links  fiber, copper, radio, satellite  transmission rate = bandwidth  routers: forward packets (chunks of data)

130 Introduction “Cool” internet appliances World’s smallest web server IP picture frame Web-enabled toaster + weather forecaster Internet phones

131 Introduction What’s the Internet:  protocols control sending, receiving of msgs  e.g., TCP, IP, HTTP, Skype, Ethernet  Internet: “network of networks”  loosely hierarchical  public Internet versus private intranet  Internet standards  RFC: Request for comments  IETF: Internet Engineering Task Force Home network Institutional network Mobile network Global ISP Regional ISP

132 Introduction What’s the Internet: a service view  communication infrastructure enables distributed applications:  Web, VoIP, , games, e-commerce, file sharing  communication services provided to apps:  reliable data delivery from source to destination  “best effort” (unreliable) data delivery

133 Introduction What’s a protocol? human protocols:  “what’s the time?”  “I have a question”  introductions … specific msgs sent … specific actions taken when msgs received, or other events network protocols:  machines rather than humans  all communication activity in Internet governed by protocols protocols define format, order of msgs sent and received among network entities, and actions taken on msg transmission, receipt

134 Introduction What’s a protocol? a human protocol and a computer network protocol: Q: Other human protocols? Hi Got the time? 2:00 TCP connection request TCP connection response Get time

135 Introduction Chapter 1: roadmap 1.1 What is the Internet? 1.2 Network edge  end systems, access networks, links 1.3 Network core  circuit switching, packet switching, network structure 1.4 Delay, loss and throughput in packet-switched networks 1.5 Protocol layers, service models 1.6 Networks under attack: security 1.7 History

136 Introduction A closer look at network structure:  network edge: applications and hosts  access networks, physical media: wired, wireless communication links  network core:  interconnected routers  network of networks

137 Introduction The network edge:  end systems (hosts):  run application programs  e.g. Web,  at “edge of network” client/server peer-peer  client/server model  client host requests, receives service from always-on server  e.g. Web browser/server; client/server  peer-peer model:  minimal (or no) use of dedicated servers  e.g. Skype, BitTorrent

138 Introduction Access networks and physical media Q: How to connect end systems to edge router?  residential access nets  institutional access networks (school, company)  mobile access networks Keep in mind:  bandwidth (bits per second) of access network?  shared or dedicated?

139 telephone network Internet home dial-up modem ISP modem (e.g., AOL) home PC central office  Uses existing telephony infrastructure  Home is connected to central office  up to 56Kbps direct access to router (often less)  Can’t surf and phone at same time: not “always on” Dial-up Modem

140 telephone network DSL modem home PC home phone Internet DSLAM Existing phone line: 0-4KHz phone; 4-50KHz upstream data; 50KHz-1MHz downstream data splitter central office Digital Subscriber Line (DSL)  Also uses existing telephone infrastruture  up to 1 Mbps upstream (today typically < 256 kbps)  up to 8 Mbps downstream (today typically < 1 Mbps)  dedicated physical line to telephone central office

141 Introduction Residential access: cable modems  Does not use telephone infrastructure  Instead uses cable TV infrastructure  HFC: hybrid fiber coax  asymmetric: up to 30Mbps downstream, 2 Mbps upstream  network of cable and fiber attaches homes to ISP router  homes share access to router  unlike DSL, which has dedicated access

142 Introduction Residential access: cable modems Diagram:

143 Introduction Cable Network Architecture: Overview home cable headend cable distribution network (simplified) Typically 500 to 5,000 homes

144 Introduction Cable Network Architecture: Overview home cable headend cable distribution network server(s)

145 Introduction Cable Network Architecture: Overview home cable headend cable distribution network (simplified)

146 Introduction Cable Network Architecture: Overview home cable headend cable distribution network Channels VIDEOVIDEO VIDEOVIDEO VIDEOVIDEO VIDEOVIDEO VIDEOVIDEO VIDEOVIDEO DATADATA DATADATA CONTROLCONTROL FDM (more shortly):

147 ONT OLT central office optical splitter ONT optical fiber optical fibers Internet Fiber to the Home  Optical links from central office to the home  Two competing optical technologies:  Passive Optical network (PON)  Active Optical Network (PAN)  Much higher Internet rates; fiber also carries television and phone services

148 100 Mbps 1 Gbps server Ethernet switch Institutional router To Institution’s ISP Ethernet Internet access  Typically used in companies, universities, etc  10 Mbs, 100Mbps, 1Gbps, 10Gbps Ethernet  Today, end systems typically connect into Ethernet switch

149 Introduction Wireless access networks  shared wireless access network connects end system to router  via base station aka “access point”  wireless LANs:  b/g (WiFi): 11 or 54 Mbps  wider-area wireless access  provided by telco operator  ~1Mbps over cellular system (EVDO, HSDPA)  next up (?): WiMAX (10’s Mbps) over wide area base station mobile hosts router

150 Introduction Home networks Typical home network components:  DSL or cable modem  router/firewall/NAT  Ethernet  wireless access point wireless access point wireless laptops router/ firewall cable modem to/from cable headend Ethernet

151 Introduction Physical Media  Bit: propagates between transmitter/rcvr pairs  physical link: what lies between transmitter & receiver  guided media:  signals propagate in solid media: copper, fiber, coax  unguided media:  signals propagate freely, e.g., radio Twisted Pair (TP)  two insulated copper wires  Category 3: traditional phone wires, 10 Mbps Ethernet  Category 5: 100Mbps Ethernet

152 Introduction Physical Media: coax, fiber Coaxial cable:  two concentric copper conductors  bidirectional  baseband:  single channel on cable  legacy Ethernet  broadband:  multiple channels on cable  HFC Fiber optic cable:  glass fiber carrying light pulses, each pulse a bit  high-speed operation:  high-speed point-to-point transmission (e.g., 10’s- 100’s Gps)  low error rate: repeaters spaced far apart ; immune to electromagnetic noise

153 Introduction Physical media: radio  signal carried in electromagnetic spectrum  no physical “wire”  bidirectional  propagation environment effects:  reflection  obstruction by objects  interference Radio link types:  terrestrial microwave  e.g. up to 45 Mbps channels  LAN (e.g., Wifi)  11Mbps, 54 Mbps  wide-area (e.g., cellular)  3G cellular: ~ 1 Mbps  satellite  Kbps to 45Mbps channel (or multiple smaller channels)  270 msec end-end delay  geosynchronous versus low altitude

154 Introduction Chapter 1: roadmap 1.1 What is the Internet? 1.2 Network edge  end systems, access networks, links 1.3 Network core  circuit switching, packet switching, network structure 1.4 Delay, loss and throughput in packet-switched networks 1.5 Protocol layers, service models 1.6 Networks under attack: security 1.7 History

155 Introduction The Network Core  mesh of interconnected routers  the fundamental question: how is data transferred through net?  circuit switching: dedicated circuit per call: telephone net  packet-switching: data sent thru net in discrete “chunks”

156 Introduction Network Core: Circuit Switching End-end resources reserved for “call”  link bandwidth, switch capacity  dedicated resources: no sharing  circuit-like (guaranteed) performance  call setup required

157 Introduction Network Core: Circuit Switching network resources (e.g., bandwidth) divided into “pieces”  pieces allocated to calls  resource piece idle if not used by owning call (no sharing)  dividing link bandwidth into “pieces”  frequency division  time division

158 Introduction Circuit Switching: FDM and TDM FDM frequency time TDM frequency time 4 users Example:

159 Introduction Numerical example  How long does it take to send a file of 640,000 bits from host A to host B over a circuit-switched network?  All links are Mbps  Each link uses TDM with 24 slots/sec  500 msec to establish end-to-end circuit Let’s work it out!

160 Introduction Network Core: Packet Switching each end-end data stream divided into packets  user A, B packets share network resources  each packet uses full link bandwidth  resources used as needed resource contention:  aggregate resource demand can exceed amount available  congestion: packets queue, wait for link use  store and forward: packets move one hop at a time  Node receives complete packet before forwarding Bandwidth division into “pieces” Dedicated allocation Resource reservation

161 Introduction Packet Switching: Statistical Multiplexing Sequence of A & B packets does not have fixed pattern, bandwidth shared on demand  statistical multiplexing. TDM: each host gets same slot in revolving TDM frame. A B C 100 Mb/s Ethernet 1.5 Mb/s D E statistical multiplexing queue of packets waiting for output link

162 Introduction Packet-switching: store-and-forward  takes L/R seconds to transmit (push out) packet of L bits on to link at R bps  store and forward: entire packet must arrive at router before it can be transmitted on next link  delay = 3L/R (assuming zero propagation delay) Example:  L = 7.5 Mbits  R = 1.5 Mbps  transmission delay = 15 sec R R R L more on delay shortly …

163 Introduction Packet switching versus circuit switching  1 Mb/s link  each user:  100 kb/s when “active”  active 10% of time  circuit-switching:  10 users  packet switching:  with 35 users, probability > 10 active at same time is less than.0004 Packet switching allows more users to use network! N users 1 Mbps link Q: how did we get value ?

164 Introduction Packet switching versus circuit switching  great for bursty data  resource sharing  simpler, no call setup  excessive congestion: packet delay and loss  protocols needed for reliable data transfer, congestion control  Q: How to provide circuit-like behavior?  bandwidth guarantees needed for audio/video apps Is packet switching the definitive winner? Q: human analogies of reserved resources (circuit switching) versus on-demand allocation (packet-switching)?

165 Introduction Internet structure: network of networks  roughly hierarchical  at center: “tier-1” ISPs (e.g., Verizon, Sprint, AT&T, Cable and Wireless), national/international coverage  treat each other as equals Tier 1 ISP Tier-1 providers interconnect (peer) privately

166 Introduction Tier-1 ISP: e.g., Sprint … to/from customers peering to/from backbone ….…. … … … POP: point-of-presence

167 Introduction Internet structure: network of networks  “Tier-2” ISPs: smaller (often regional) ISPs  Connect to one or more tier-1 ISPs, possibly other tier-2 ISPs Tier 1 ISP Tier-2 ISP Tier-2 ISP pays tier-1 ISP for connectivity to rest of Internet  tier-2 ISP is customer of tier-1 provider Tier-2 ISPs also peer privately with each other.

168 Introduction Internet structure: network of networks  “Tier-3” ISPs and local ISPs  last hop (“access”) network (closest to end systems) Tier 1 ISP Tier-2 ISP local ISP local ISP local ISP local ISP local ISP Tier 3 ISP local ISP local ISP local ISP Local and tier- 3 ISPs are customers of higher tier ISPs connecting them to rest of Internet

169 Introduction Internet structure: network of networks  a packet passes through many networks! Tier 1 ISP Tier-2 ISP local ISP local ISP local ISP local ISP local ISP Tier 3 ISP local ISP local ISP local ISP

170 Introduction Chapter 1: roadmap 1.1 What is the Internet? 1.2 Network edge  end systems, access networks, links 1.3 Network core  circuit switching, packet switching, network structure 1.4 Delay, loss and throughput in packet-switched networks 1.5 Protocol layers, service models 1.6 Networks under attack: security 1.7 History

171 Introduction How do loss and delay occur? packets queue in router buffers  packet arrival rate to link exceeds output link capacity  packets queue, wait for turn A B packet being transmitted (delay) packets queueing (delay) free (available) buffers: arriving packets dropped (loss) if no free buffers

172 Introduction Four sources of packet delay  1. nodal processing:  check bit errors  determine output link A B propagation transmission nodal processing queueing  2. queueing  time waiting at output link for transmission  depends on congestion level of router

173 Introduction Delay in packet-switched networks 3. Transmission delay:  R=link bandwidth (bps)  L=packet length (bits)  time to send bits into link = L/R 4. Propagation delay:  d = length of physical link  s = propagation speed in medium (~2x10 8 m/sec)  propagation delay = d/s A B propagation transmission nodal processing queueing Note: s and R are very different quantities!

174 Introduction Caravan analogy  cars “propagate” at 100 km/hr  toll booth takes 12 sec to service car (transmission time)  car~bit; caravan ~ packet  Q: How long until caravan is lined up before 2nd toll booth?  Time to “push” entire caravan through toll booth onto highway = 12*10 = 120 sec  Time for last car to propagate from 1st to 2nd toll both: 100km/(100km/hr)= 1 hr  A: 62 minutes toll booth toll booth ten-car caravan 100 km

175 Introduction Caravan analogy (more)  Cars now “propagate” at 1000 km/hr  Toll booth now takes 1 min to service a car  Q: Will cars arrive to 2nd booth before all cars serviced at 1st booth?  Yes! After 7 min, 1st car at 2nd booth and 3 cars still at 1st booth.  1st bit of packet can arrive at 2nd router before packet is fully transmitted at 1st router! toll booth toll booth ten-car caravan 100 km

176 Introduction Nodal delay  d proc = processing delay  typically a few microsecs or less  d queue = queuing delay  depends on congestion  d trans = transmission delay  = L/R, significant for low-speed links  d prop = propagation delay  a few microsecs to hundreds of msecs

177 Introduction Queueing delay (revisited)  R=link bandwidth (bps)  L=packet length (bits)  a=average packet arrival rate traffic intensity = La/R  La/R ~ 0: average queueing delay small  La/R -> 1: delays become large  La/R > 1: more “work” arriving than can be serviced, average delay infinite!

178 Introduction “Real” Internet delays and routes  What do “real” Internet delay & loss look like?  Traceroute program: provides delay measurement from source to router along end-end Internet path towards destination. For all i:  sends three packets that will reach router i on path towards destination  router i will return packets to sender  sender times interval between transmission and reply. 3 probes

179 Introduction “Real” Internet delays and routes 1 cs-gw ( ) 1 ms 1 ms 2 ms 2 border1-rt-fa5-1-0.gw.umass.edu ( ) 1 ms 1 ms 2 ms 3 cht-vbns.gw.umass.edu ( ) 6 ms 5 ms 5 ms 4 jn1-at wor.vbns.net ( ) 16 ms 11 ms 13 ms 5 jn1-so wae.vbns.net ( ) 21 ms 18 ms 18 ms 6 abilene-vbns.abilene.ucaid.edu ( ) 22 ms 18 ms 22 ms 7 nycm-wash.abilene.ucaid.edu ( ) 22 ms 22 ms 22 ms ( ) 104 ms 109 ms 106 ms 9 de2-1.de1.de.geant.net ( ) 109 ms 102 ms 104 ms 10 de.fr1.fr.geant.net ( ) 113 ms 121 ms 114 ms 11 renater-gw.fr1.fr.geant.net ( ) 112 ms 114 ms 112 ms 12 nio-n2.cssi.renater.fr ( ) 111 ms 114 ms 116 ms 13 nice.cssi.renater.fr ( ) 123 ms 125 ms 124 ms 14 r3t2-nice.cssi.renater.fr ( ) 126 ms 126 ms 124 ms 15 eurecom-valbonne.r3t2.ft.net ( ) 135 ms 128 ms 133 ms ( ) 126 ms 128 ms 126 ms 17 * * * 18 * * * 19 fantasia.eurecom.fr ( ) 132 ms 128 ms 136 ms traceroute: gaia.cs.umass.edu to Three delay measurements from gaia.cs.umass.edu to cs-gw.cs.umass.edu * means no response (probe lost, router not replying) trans-oceanic link

180 Introduction Packet loss  queue (aka buffer) preceding link in buffer has finite capacity  packet arriving to full queue dropped (aka lost)  lost packet may be retransmitted by previous node, by source end system, or not at all A B packet being transmitted packet arriving to full buffer is lost buffer (waiting area)

181 Introduction Throughput  throughput: rate (bits/time unit) at which bits transferred between sender/receiver  instantaneous: rate at given point in time  average: rate over longer period of time server, with file of F bits to send to client link capacity R s bits/sec link capacity R c bits/sec pipe that can carry fluid at rate R s bits/sec) pipe that can carry fluid at rate R c bits/sec) server sends bits (fluid) into pipe

182 Introduction Throughput (more)  R s < R c What is average end-end throughput? R s bits/sec R c bits/sec  R s > R c What is average end-end throughput? R s bits/sec R c bits/sec link on end-end path that constrains end-end throughput bottleneck link

183 Introduction Throughput: Internet scenario 10 connections (fairly) share backbone bottleneck link R bits/sec RsRs RsRs RsRs RcRc RcRc RcRc R  per-connection end-end throughput: min(R c,R s,R/10)  in practice: R c or R s is often bottleneck

184 Introduction Chapter 1: roadmap 1.1 What is the Internet? 1.2 Network edge  end systems, access networks, links 1.3 Network core  circuit switching, packet switching, network structure 1.4 Delay, loss and throughput in packet-switched networks 1.5 Protocol layers, service models 1.6 Networks under attack: security 1.7 History

185 Introduction Protocol “Layers” Networks are complex!  many “pieces”:  hosts  routers  links of various media  applications  protocols  hardware, software Question: Is there any hope of organizing structure of network? Or at least our discussion of networks?

186 Introduction Organization of air travel  a series of steps ticket (purchase) baggage (check) gates (load) runway takeoff airplane routing ticket (complain) baggage (claim) gates (unload) runway landing airplane routing

187 Introduction ticket (purchase) baggage (check) gates (load) runway (takeoff) airplane routing departure airport arrival airport intermediate air-traffic control centers airplane routing ticket (complain) baggage (claim gates (unload) runway (land) airplane routing ticket baggage gate takeoff/landing airplane routing Layering of airline functionality Layers: each layer implements a service  via its own internal-layer actions  relying on services provided by layer below

188 Introduction Why layering? Dealing with complex systems:  explicit structure allows identification, relationship of complex system’s pieces  layered reference model for discussion  modularization eases maintenance, updating of system  change of implementation of layer’s service transparent to rest of system  e.g., change in gate procedure doesn’t affect rest of system  layering considered harmful?

189 Introduction Internet protocol stack  application: supporting network applications  FTP, SMTP, HTTP  transport: process-process data transfer  TCP, UDP  network: routing of datagrams from source to destination  IP, routing protocols  link: data transfer between neighboring network elements  PPP, Ethernet  physical: bits “on the wire” application transport network link physical

190 Introduction ISO/OSI reference model  presentation: allow applications to interpret meaning of data, e.g., encryption, compression, machine- specific conventions  session: synchronization, checkpointing, recovery of data exchange  Internet stack “missing” these layers!  these services, if needed, must be implemented in application  needed? application presentation session transport network link physical

191 Introduction source application transport network link physical HtHt HnHn M segment HtHt datagram destination application transport network link physical HtHt HnHn HlHl M HtHt HnHn M HtHt M M network link physical link physical HtHt HnHn HlHl M HtHt HnHn M HtHt HnHn M HtHt HnHn HlHl M router switch Encapsulation message M HtHt M HnHn frame

192 Introduction Chapter 1: roadmap 1.1 What is the Internet? 1.2 Network edge  end systems, access networks, links 1.3 Network core  circuit switching, packet switching, network structure 1.4 Delay, loss and throughput in packet-switched networks 1.5 Protocol layers, service models 1.6 Networks under attack: security 1.7 History

193 Introduction Network Security  The field of network security is about:  how bad guys can attack computer networks  how we can defend networks against attacks  how to design architectures that are immune to attacks  Internet not originally designed with (much) security in mind  original vision: “a group of mutually trusting users attached to a transparent network”  Internet protocol designers playing “catch-up”  Security considerations in all layers!

194 Introduction Bad guys can put malware into hosts via Internet  Malware can get in host from a virus, worm, or trojan horse.  Spyware malware can record keystrokes, web sites visited, upload info to collection site.  Infected host can be enrolled in a botnet, used for spam and DDoS attacks.  Malware is often self-replicating: from an infected host, seeks entry into other hosts

195 Introduction Bad guys can put malware into hosts via Internet  Trojan horse  Hidden part of some otherwise useful software  Today often on a Web page (Active-X, plugin)  Virus  infection by receiving object (e.g., attachment), actively executing  self-replicating: propagate itself to other hosts, users  Worm:  infection by passively receiving object that gets itself executed  self- replicating: propagates to other hosts, users Sapphire Worm: aggregate scans/sec in first 5 minutes of outbreak (CAIDA, UWisc data)

196 Introduction Bad guys can attack servers and network infrastructure  Denial of service (DoS): attackers make resources (server, bandwidth) unavailable to legitimate traffic by overwhelming resource with bogus traffic 1. select target 2. break into hosts around the network (see botnet) 3. send packets toward target from compromised hosts target

197 Introduction The bad guys can sniff packets Packet sniffing:  broadcast media (shared Ethernet, wireless)  promiscuous network interface reads/records all packets (e.g., including passwords!) passing by A B C src:B dest:A payload  Wireshark software is a (free) packet-sniffer

198 Introduction The bad guys can use false source addresses  IP spoofing: send packet with false source address A B C src:B dest:A payload

199 Introduction The bad guys can record and playback  record-and-playback : sniff sensitive info (e.g., password), and use later  password holder is that user from system point of view A B C src:B dest:A user: B; password: foo

200 Introduction Network Security  more throughout this course  chapter 8: focus on security  crypographic techniques: obvious uses and not so obvious uses

201 Introduction Chapter 1: roadmap 1.1 What is the Internet? 1.2 Network edge  end systems, access networks, links 1.3 Network core  circuit switching, packet switching, network structure 1.4 Delay, loss and throughput in packet-switched networks 1.5 Protocol layers, service models 1.6 Networks under attack: security 1.7 History

202 Introduction Internet History  1961: Kleinrock - queueing theory shows effectiveness of packet- switching  1964: Baran - packet- switching in military nets  1967: ARPAnet conceived by Advanced Research Projects Agency  1969: first ARPAnet node operational  1972:  ARPAnet public demonstration  NCP (Network Control Protocol) first host-host protocol  first program  ARPAnet has 15 nodes : Early packet-switching principles

203 Introduction Internet History  1970: ALOHAnet satellite network in Hawaii  1974: Cerf and Kahn - architecture for interconnecting networks  1976: Ethernet at Xerox PARC  ate70’s: proprietary architectures: DECnet, SNA, XNA  late 70’s: switching fixed length packets (ATM precursor)  1979: ARPAnet has 200 nodes Cerf and Kahn’s internetworking principles:  minimalism, autonomy - no internal changes required to interconnect networks  best effort service model  stateless routers  decentralized control define today’s Internet architecture : Internetworking, new and proprietary nets

204 Introduction Internet History  1983: deployment of TCP/IP  1982: smtp protocol defined  1983: DNS defined for name-to-IP- address translation  1985: ftp protocol defined  1988: TCP congestion control  new national networks: Csnet, BITnet, NSFnet, Minitel  100,000 hosts connected to confederation of networks : new protocols, a proliferation of networks

205 Introduction Internet History  Early 1990’s: ARPAnet decommissioned  1991: NSF lifts restrictions on commercial use of NSFnet (decommissioned, 1995)  early 1990s: Web  hypertext [Bush 1945, Nelson 1960’s]  HTML, HTTP: Berners-Lee  1994: Mosaic, later Netscape  late 1990’s: commercialization of the Web Late 1990’s – 2000’s:  more killer apps: instant messaging, P2P file sharing  network security to forefront  est. 50 million host, 100 million+ users  backbone links running at Gbps 1990, 2000’s: commercialization, the Web, new apps

206 Introduction Internet History 2007:  ~500 million hosts  Voice, Video over IP  P2P applications: BitTorrent (file sharing) Skype (VoIP), PPLive (video)  more applications: YouTube, gaming  wireless, mobility

207 Internet 2010 Introduction 1-207

208 Internet 2010 Introduction 1-208

209 Facebook Introduction 1-209


Download ppt "Introduction 1-1 Protocoles réseaux Sommaire (prévision):  Introduction  Rappels programmation réseau (java)  Modèles  Systèmes de transitions, "safety."

Similar presentations


Ads by Google