• No results found

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

N/A
N/A
Protected

Academic year: 2021

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

Copied!
59
0
0

Loading.... (view fulltext now)

Full text

(1)
(2)
(3)

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

application viewpoint

UDP provides unreliable transfer

of groups of bytes (“datagrams”)

between client and server

(4)

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

(5)

Client/server socket interaction: UDP

Server (running on

hostid

)

read datagram from

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

(6)

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

(7)

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");

Create

input stream

Create

client socket

Translate

hostname to IP

address

using DNS

(8)

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

(9)

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)

{

Create

datagram socket

at port 9876

(10)

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

(11)

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?

(12)

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)

(13)

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);

}

(14)

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)

(15)

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 )

(16)

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);

}

}

}

(17)

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

(18)

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

}

(19)

Envoyer et recevoir

public void send(DatagramPacket dp)

throws IOException

public void receive(DatagramPacket dp)

(20)

Un exemple: Echo

UDPServeur

UDPEchoServeur

UDPEchoClient

SenderThread

ReceiverThread

(21)

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); }

(22)

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); }

} }

(23)

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);

}

(24)

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); } }

} }

(25)

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() {

(26)

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

(27)

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( )

(28)

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

(29)
(30)

R1

R2

R3

R4

source

duplication

R1

R2

R3

R4

in-network

duplication

duplicate creation/transmission

duplicate

duplicate

Broadcast Routing

Deliver packets from srce to all other nodes

Source duplication is inefficient:

Source duplication: how does source

(31)

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

(32)

A

B

G

D

E

c

F

A

B

G

D

E

c

F

(a) Broadcast initiated at A

(b) Broadcast initiated at D

Spanning Tree

First construct a spanning tree

Nodes forward copies only along spanning

(33)

A

B

D

c

2

3

4

A

B

D

c

Spanning Tree: Creation

Center node

Each node sends unicast join message to center

node

Message forwarded until it arrives at a node already

(34)

Multicast

Groupe: adresse IP de classe D

Un hôte peut joindre un groupe

Protocole pour établir les groupes (IGMP)

(35)

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

(36)

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

(37)

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)

(38)

Shortest Path Tree

mcast forwarding tree: tree of shortest

path routes from source to all receivers

Dijkstra’s algorithm

R1

R2

R3

R4

R5

R6

R7

2

1

6

3

4

5

i

router with attached

group member

router with no attached

group member

link used for forwarding,

i indicates order link

added by algorithm

LEGEND

(39)

Reverse Path Forwarding

if

(mcast datagram received on incoming link

on shortest path back to center)

then

flood datagram onto all outgoing links

rely on router’s knowledge of unicast

shortest path from it to sender

(40)

Reverse Path Forwarding: example

result is a source-specific

reverse

SPT

may be a bad choice with asymmetric links

R1

R2

R3

R4

R5

R6

R7

router with attached

group member

router with no attached

group member

datagram will be

forwarded

LEGEND

S: source

datagram will not be

forwarded

(41)

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

R1

R2

R4

router with attached

group member

router with no attached

group member

LEGEND

S: source

(42)

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

(43)

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

(44)

Center-based trees: an example

Suppose R6 chosen as center:

R1

R2

R3

R4

R5

R6

R7

router with attached

group member

router with no attached

group member

path order in which join

messages generated

LEGEND

2

1

3

1

(45)

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

(46)

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

(47)

Tunneling

Q:

How to connect “islands” of multicast

routers in a “sea” of unicast routers?

 

mcast datagram encapsulated inside “normal”

(non-multicast-addressed) datagram

(48)

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”

(49)

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

non-group-router processing

profligate

Sparse

:

no membership until

routers explicitly join

receiver- driven

construction of mcast

tree (e.g., center-based)

bandwidth and

non-group-router processing

(50)

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

(51)

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

R1

R2

R3

R4

R5

R6

R7

join

join

join

(52)

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!”

R1

R2

R3

R4

R5

R6

R7

join

join

join

all data multicast

from rendezvous

point

rendezvous

point

(53)

Multicast

Géré par les routeurs

Pas de garantie…

Importance du ttl

(Évaluation)

Local:0

Sous-réseau local:1

Pays:48

Continent:64

(54)

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

(55)

Sockets multicast

Extension de

DatagramSocket

public class MulticastSocket extends

DatagramSocket

Principe:

Créer une

MulticastSocket

Rejoindre un group:

joinGroup()

Créer

DatagramPacket

(56)

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...

(57)

Création

try {

MulticastSocket ms = new MulticastSocket(null);

ms.setReuseAddress(false);

SocketAddress address = new

InetSocketAddress(4000);

ms.bind(address);

// receive datagrams...

}catch (SocketException ex)

(58)

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);

}

(59)

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);

References

Related documents

The OpenStage 30T/40/40G/40T always requires a local power supply (SMPS mains adapter, must be ordered separately) if an OpenStage Busy Lamp Field 40 is connected.. The PNOTE

• Does your organisation handle, hold or store customers information and publicise all your services via a website?.. Provision of services

[r]

Europe of the regions, along with the movement for a European Union and for multiculturalism reject common nationality as the common bond on which political units must be based..

El objetivo de este artículo es, por una parte, analizar si el número sin precedentes de alcaldesas y concejalas escogidas en las elecciones locales de 2014 ha

Columns (2), (3), and (4) give, in order, the DB SCAN algorithm neighborhood radius; maximum mass- density ratio of galaxies in a shell surrounding a candidate group to the

In the first section of RM-218, Quine introduces the notion of aggregation of individual orderings function, denoted by F (then we have a social ordering given by F ( R 1 , ..., R n

FORENSIC ACCOUNTING: A COMPREHENSIVE GUIDE TO CONDUCTING FINANCIAL FRAUD INVESTIGATIONS FOAC/14/01... This product is intended to serve solely as an aid in