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

Similar documents
Rappels programma,on réseau Java- suite. C. Delporte M2- Internet Rappel Java 1

Data Communication & Networks G

Network Programming using sockets

DNS: Domain Names. DNS: Domain Name System. DNS: Root name servers. DNS name servers

Socket programming. Socket Programming. Languages and Platforms. Sockets. Rohan Murty Hitesh Ballani. Last Modified: 2/8/2004 8:30:45 AM

Goal: learn how to build client/server application that communicate using sockets. An interface between application and network

IP Multicasting. Applications with multiple receivers

Chapter 2: Application layer

Transport layer protocols. Message destination: Socket +Port. Asynchronous vs. Synchronous. Operations of Request-Reply. Sockets

NETWORK PROGRAMMING IN JAVA USING SOCKETS

Socket Programming in Java

CISC 4700 L01 Network & Client- Server Programming Spring Harold, Chapter 8: Sockets for Clients

Abstract Stream Socket Service

SSC - Communication and Networking Java Socket Programming (II)

Network Communication

Java Programming: Sockets in Java

CHAPTER 10 IP MULTICAST

Socket-based Network Communication in J2SE and J2ME

Java Network. Slides prepared by : Farzana Rahman

Division of Informatics, University of Edinburgh

Socket Programming. Announcement. Lectures moved to

Lesson: All About Sockets

- Multicast - Types of packets

Network-based Applications. Pavani Diwanji David Brown JavaSoft

TP1 : Correction. Rappels : Stream, Thread et Socket TCP

Data Communications & Networks. Session 2 Main Theme Application Layer. Dr. Jean-Claude Franchitti

Introduction to IP Multicast Routing

Network/Socket Programming in Java. Rajkumar Buyya

The difference between TCP/IP, UDP/IP and Multicast sockets. How servers and clients communicate over sockets

Internet Packets. Forwarding Datagrams

String sentence = new String(receivePacket.getData()); InetAddress IPAddress = receivepacket.getaddress(); int port = receivepacket.

Application Development with TCP/IP. Brian S. Mitchell Drexel University

Datagram-based network layer: forwarding; routing. Additional function of VCbased network layer: call setup.

Internet Protocol Multicast

CS335 Sample Questions for Exam #2

The Benefits of Layer 3 Routing at the Network Edge. Peter McNeil Product Marketing Manager L-com Global Connectivity

IP - The Internet Protocol

Creating a Simple, Multithreaded Chat System with Java

Communicating with a Barco projector over network. Technical note

Transport Layer Protocols

Network layer: Overview. Network layer functions IP Routing and forwarding

IP Network Layer. Datagram ID FLAG Fragment Offset. IP Datagrams. IP Addresses. IP Addresses. CSCE 515: Computer Network Programming TCP/IP

CS 457 Lecture 19 Global Internet - BGP. Fall 2011

Efficient Video Distribution Networks with.multicast: IGMP Querier and PIM-DM

Course Overview: Learn the essential skills needed to set up, configure, support, and troubleshoot your TCP/IP-based network.

Configuration Examples. D-Link Switches L3 Features and Examples IP Multicast Routing

Mail User Agent Project

Objectives. The Role of Redundancy in a Switched Network. Layer 2 Loops. Broadcast Storms. More problems with Layer 2 loops

Introduction to IP v6

Multicast for Enterprise Video Streaming

Data Networking and Architecture. Delegates should have some basic knowledge of Internet Protocol and Data Networking principles.

Introduction to LAN/WAN. Network Layer

Computer Networks. Main Functions

Transparent Redirection of Network Sockets 1

Socket Programming. A er learning the contents of this chapter, the reader will be able to:

Ethernet. Ethernet. Network Devices

Internet Firewall CSIS Packet Filtering. Internet Firewall. Examples. Spring 2011 CSIS net15 1. Routers can implement packet filtering

Chapter 11. User Datagram Protocol (UDP)

Layer 3 Routing User s Manual

Variable length subnetting

A Tutorial on Socket Programming in Java

College 5, Routing, Internet. Host A. Host B. The Network Layer: functions

VXLAN: Scaling Data Center Capacity. White Paper

Learning Outcomes. Networking. Sockets. TCP/IP Networks. Hostnames and DNS TCP/IP

Hands on Workshop. Network Performance Monitoring and Multicast Routing. Yasuichi Kitamura NICT Jin Tanaka KDDI/NICT APAN-JP NOC

A Modified Shared-tree Multicast Routing Protocol in Ad Hoc Network

Building a Multi-Threaded Web Server

20. Switched Local Area Networks

Transparent Redirection of Network Sockets 1

Route Discovery Protocols

Transport Layer Services Mul9plexing/Demul9plexing. Transport Layer Services

Lecture 8. IP Fundamentals

Multicast: Conformance and Performance Testing

LAN Switching Computer Networking. Switched Network Advantages. Hubs (more) Hubs. Bridges/Switches, , PPP. Interconnecting LANs

Компјутерски Мрежи NAT & ICMP

IP Routing Features. Contents

Explicit Multicast Routing

Network Programming TDC 561

RARP: Reverse Address Resolution Protocol

8.2 The Internet Protocol

Final for ECE374 05/06/13 Solution!!

Internet Protocols Fall Lectures 7-8 Andreas Terzis

Distance Vector Multicast Routing Protocol

Faculty of Engineering Computer Engineering Department Islamic University of Gaza Network Chapter# 19 INTERNETWORK OPERATION

04 Internet Protocol (IP)

Question1-part2 What undesirable consequences might there be in having too long a DNS cache entry lifetime?

Voice over IP: RTP/RTCP The transport layer

Protocol Specification & Design. The Internet and its Protocols. Course Outline (trivia) Introduction to the Subject Teaching Methods

Note! The problem set consists of two parts: Part I: The problem specifications pages Part II: The answer pages

CS Computer Networks 1: Routing Algorithms

Answers to Sample Questions on Network Layer

Network Layers. CSC358 - Introduction to Computer Networks

Performance Evaluation of DVMRP Multicasting Network over ICMP Ping Flood for DDoS

Wide Area Networks. Learning Objectives. LAN and WAN. School of Business Eastern Illinois University. (Week 11, Thursday 3/22/2007)

Based on Computer Networking, 4 th Edition by Kurose and Ross

Transcription:

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

UDP H. Fauconnier M2-Internet Java 2

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 M2-Internet Java 3

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 H. Fauconnier M2-Internet Java 4

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

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

Example: Java client (UDP) import java.io.*; import java.net.*; Create input stream Create client socket Translate hostname to IP address using DNS 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(); H. Fauconnier M2-Internet Java 7

Example: Java client (UDP), cont. Create datagram with data-to-send, length, IP addr, port Send datagram to server Read datagram from server 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(); H. Fauconnier M2-Internet Java 8

Example: Java server (UDP) import java.io.*; import java.net.*; Create datagram socket at port 9876 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]; Create space for received datagram H. Fauconnier Receive datagram while(true) { DatagramPacket receivepacket = new DatagramPacket(receiveData, receivedata.length); serversocket.receive(receivepacket); M2-Internet Java 9

Example: Java server (UDP), cont Get IP addr port #, of sender String sentence = new String(receivePacket.getData()); InetAddress IPAddress = receivepacket.getaddress(); int port = receivepacket.getport(); Create datagram to send to client Write out datagram to socket H. Fauconnier String capitalizedsentence = sentence.touppercase(); senddata = capitalizedsentence.getbytes(); DatagramPacket sendpacket = new DatagramPacket(sendData, senddata.length, IPAddress, port); serversocket.send(sendpacket); End of while loop, loop back and wait for another datagram M2-Internet Java 10

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? H. Fauconnier M2-Internet Java 11

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 port) length, SocketAddress destination, int H. Fauconnier M2-Internet Java 12

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 13

Méthodes Adresses public InetAddress getaddress( ) public int getport( ) public SocketAddress getsocketaddress( ) public void setaddress(inetaddress remote) public void setport(int port) public void setaddress(socketaddress remote) H. Fauconnier M2-Internet Java 14

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 15

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 16

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 17

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 18

Envoyer et recevoir public void send(datagrampacket dp) throws IOException public void receive(datagrampacket dp) throws IOException H. Fauconnier M2-Internet Java 19

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

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 21

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 22

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 23

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 24

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 25

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 26

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 void disconnect( ) public int getport( ) public InetAddress getinetaddress( ) public InetAddress getremotesocketaddress( ) H. Fauconnier M2-Internet Java 27

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 28

Multicast H. Fauconnier M2-Internet Java 29

Broadcast Routing Deliver packets from srce to all other nodes Source duplication is inefficient: duplicate R1 duplicate creation/transmission R1 R2 R2 duplicate R3 R4 R3 R4 source duplication in-network duplication Source duplication: how does source determine recipient addresses H. Fauconnier M2-Internet Java 4-30

In-network duplication Flooding: when node receives brdcst pckt, sends copy to all neighbors Problems: cycles & broadcast storm Controlled flooding: node only brdcsts pkt if it hasn t brdcst same packet before Node keeps track of pckt ids already brdcsted Or reverse path forwarding (RPF): only forward pckt if it arrived on shortest path between node and source Spanning tree No redundant packets received by any node H. Fauconnier M2-Internet Java 4-31

Spanning Tree First construct a spanning tree Nodes forward copies only along spanning tree A A c B c B F E D F E D (a) Broadcast initiated at A G (b) Broadcast initiated at D G H. Fauconnier M2-Internet Java 4-32

Spanning Tree: Creation Center node Each node sends unicast join message to center node Message forwarded until it arrives at a node already belonging to spanning tree A A c 3 B c B F 1 4 E 2 D 5 F E D G G (a) Stepwise construction of spanning tree H. Fauconnier (b) Constructed spanning tree M2-Internet Java 4-33

Multicast Groupe: adresse IP de classe D Un hôte peut joindre un groupe Protocole pour établir les groupes (IGMP) Protocole et algorithme pour le routage H. Fauconnier M2-Internet Java 4-34

IGMP IGMP (internet Group Management Protocol Entre un hôte et son routeur (multicast) Membership_query: du routeur vers tous les hôtes pour déterminer quels hôtes appartiennent à quels groupe Membership_report: des hôtes vers le routeur Membership_leave: pour quitter un groupe (optionnel) H. Fauconnier M2-Internet Java 4-35

Multicast Routing: Problem Statement Goal: find a tree (or trees) connecting routers having local mcast group members tree: not all paths between routers used source-based: different tree from each sender to rcvrs shared-tree: same tree used by all group members Shared tree Source-based trees H. Fauconnier 1-36 M2-Internet Java

Approaches for building mcast trees Approaches: source-based tree: one tree per source shortest path trees reverse path forwarding group-shared tree: group uses one tree minimal spanning (Steiner) center-based trees we first look at basic approaches, then specific protocols adopting these approaches H. Fauconnier 1-37 M2-Internet Java

Shortest Path Tree mcast forwarding tree: tree of shortest path routes from source to all receivers Dijkstra s algorithm S: source R1 1 R2 3 4 2 R4 5 R5 LEGEND router with attached group member router with no attached group member R3 R6 6 R7 i link used for forwarding, i indicates order link added by algorithm H. Fauconnier 1-38 M2-Internet Java

Reverse Path Forwarding rely on router s knowledge of unicast shortest path from it to sender each router has simple forwarding behavior: if (mcast datagram received on incoming link on shortest path back to center) then flood datagram onto all outgoing links else ignore datagram H. Fauconnier 1-39 M2-Internet Java

Reverse Path Forwarding: example S: source R2 R1 R4 R5 LEGEND router with attached group member router with no attached group member R3 R6 R7 datagram will be forwarded datagram will not be forwarded result is a source-specific reverse SPT may be a bad choice with asymmetric links H. Fauconnier 1-40 M2-Internet Java

Reverse Path Forwarding: pruning forwarding tree contains subtrees with no mcast group members no need to forward datagrams down subtree prune msgs sent upstream by router with no downstream group members S: source LEGEND R1 R4 router with attached group member R3 R2 R6 P P R7 R5 P router with no attached group member prune message links with multicast forwarding H. Fauconnier 1-41 M2-Internet Java

Shared-Tree: Steiner Tree Steiner Tree: minimum cost tree connecting all routers with attached group members problem is NP-complete excellent heuristics exists not used in practice: computational complexity information about entire network needed monolithic: rerun whenever a router needs to join/leave H. Fauconnier 1-42 M2-Internet Java

Center-based trees single delivery tree shared by all one router identified as center of tree to join: edge router sends unicast join-msg addressed to center router join-msg processed by intermediate routers and forwarded towards center join-msg either hits existing tree branch for this center, or arrives at center path taken by join-msg becomes new branch of tree for this router H. Fauconnier 1-43 M2-Internet Java

Center-based trees: an example Suppose R6 chosen as center: LEGEND R1 3 R4 router with attached group member R3 R2 1 R6 2 R7 R5 1 router with no attached group member path order in which join messages generated H. Fauconnier 1-44 M2-Internet Java

Internet Multicasting Routing: DVMRP DVMRP: distance vector multicast routing protocol, RFC1075 flood and prune: reverse path forwarding, source-based tree RPF tree based on DVMRP s own routing tables constructed by communicating DVMRP routers no assumptions about underlying unicast initial datagram to mcast group flooded everywhere via RPF routers not wanting group: send upstream prune msgs H. Fauconnier 1-45 M2-Internet Java

DVMRP: continued soft state: DVMRP router periodically (1 min.) forgets branches are pruned: mcast data again flows down unpruned branch downstream router: reprune or else continue to receive data routers can quickly regraft to tree following IGMP join at leaf odds and ends commonly implemented in commercial routers Mbone routing done using DVMRP H. Fauconnier 1-46 M2-Internet Java

Tunneling Q: How to connect islands of multicast routers in a sea of unicast routers? physical topology logical topology mcast datagram encapsulated inside normal (non-multicastaddressed) datagram normal IP datagram sent thru tunnel via regular IP unicast to receiving mcast router receiving mcast router unencapsulates to get mcast datagram H. Fauconnier 1-47 M2-Internet Java

PIM: Protocol Independent Multicast not dependent on any specific underlying unicast routing algorithm (works with all) two different multicast distribution scenarios : Dense: group members densely packed, in close proximity. bandwidth more plentiful Sparse: # networks with group members small wrt # interconnected networks group members widely dispersed bandwidth not plentiful H. Fauconnier 1-48 M2-Internet Java

Consequences of Sparse-Dense Dichotomy: Dense group membership by routers assumed until routers explicitly prune data-driven construction on mcast tree (e.g., RPF) bandwidth and nongroup-router processing profligate Sparse: no membership until routers explicitly join receiver- driven construction of mcast tree (e.g., center-based) bandwidth and non-grouprouter processing conservative H. Fauconnier 1-49 M2-Internet Java

PIM- Dense Mode flood-and-prune RPF, similar to DVMRP but underlying unicast protocol provides RPF info for incoming datagram less complicated (less efficient) downstream flood than DVMRP reduces reliance on underlying routing algorithm has protocol mechanism for router to detect it is a leaf-node router H. Fauconnier 1-50 M2-Internet Java

PIM - Sparse Mode center-based approach router sends join msg to rendezvous point (RP) intermediate routers update state and forward join after joining via RP, router can switch to source-specific tree increased performance: less concentration, shorter paths R3 R2 R1 join join all data multicast from rendezvous point R6 join R4 R5 R7 rendezvous point H. Fauconnier 1-51 M2-Internet Java

PIM - Sparse Mode sender(s): unicast data to RP, which distributes down RP-rooted tree RP can extend mcast tree upstream to source RP can send stop msg if no attached receivers no one is listening! R3 R2 R1 join join all data multicast from rendezvous point R6 join R4 R5 R7 rendezvous point H. Fauconnier 1-52 M2-Internet Java

Multicast Géré par les routeurs Pas de garantie Importance du ttl (Évaluation) Local:0 Sous-réseau local:1 Pays:48 Continent:64 Le monde:255 H. Fauconnier M2-Internet Java 4-53

Multicast Un groupe est identifié par une adresse IP (classe D) entre 224.0.0.0 et 239.255.255.255 Une adresse multicast peut avoir un nom Exemple ntp.mcast.net 224.0.1.1 H. Fauconnier M2-Internet Java 4-54

Sockets multicast Extension de DatagramSocket public class MulticastSocket extends DatagramSocket Principe: Créer une MulticastSocket Rejoindre un group: joingroup() Créer DatagramPacket Receive() leavegroup() Close() H. Fauconnier M2-Internet Java 55

Création try { MulticastSocket ms = new MulticastSocket( ); // send datagrams... catch (SocketException se){system.err.println(se); ------- try { SocketAddress address = new InetSocketAddress("192.168.254.32", 4000); MulticastSocket ms = new MulticastSocket(address); // receive datagrams... catch (SocketException ex) {System.err.println(ex); H. Fauconnier M2-Internet Java 56

Création try { MulticastSocket ms = new MulticastSocket(null); ms.setreuseaddress(false); SocketAddress address = new InetSocketAddress(4000); ms.bind(address); // receive datagrams... catch (SocketException ex) { System.err.println(ex); H. Fauconnier M2-Internet Java 57

Rejoindre try { MulticastSocket ms = new MulticastSocket(4000); InetAddress ia = InetAddress.getByName("224.2.2.2"); ms.joingroup(ia); byte[] buffer = new byte[8192]; while (true) { DatagramPacket dp = new DatagramPacket(buffer, buffer.length); ms.receive(dp); String s = new String(dp.getData( ), "8859_1"); System.out.println(s); catch (IOException ex) { System.err.println(ex); H. Fauconnier M2-Internet Java 58

send try { InetAddress ia = InetAddress.getByName("experiment.mcast.net"); byte[] data = "un packet \r\n".getbytes( ); int port = 4000; DatagramPacket dp = new DatagramPacket(data, data.length, ia, port); MulticastSocket ms = new MulticastSocket( ); ms.send(dp,64); catch (IOException ex) {System.err.println(ex); H. Fauconnier M2-Internet Java 59