You are on page 1of 59

Socket UDP

H. Fauconnier M2-Internet Java 1-1


UDP

H. Fauconnier M2-Internet Java 2


Socket programming with UDP

UDP: no “connection” between


client and server
 no handshaking
 sender explicitly attaches application viewpoint
IP address and port of
destination to each segment UDP provides unreliable transfer
of groups of bytes (“datagrams”)
 OS attaches IP address and
between client and server
port of sending socket to
each segment
 Server can extract IP
address, port of sender Note: the official terminology
from received segment 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, create socket,


port= x. clientSocket =
serverSocket = DatagramSocket()
DatagramSocket()
Create datagram with server IP and
port=x; send datagram via
read datagram from clientSocket
serverSocket

write reply to
serverSocket
specifying read datagram from
client address, clientSocket
port number close
clientSocket

H. Fauconnier M2-Internet Java 5


Example: Java client (UDP)
keyboard monitor

inFromUser
input
stream

Client
Process
process Input: receives
packet (recall
Output: sends thatTCP received
packet (recall “byte stream”)

receivePacket
sendPacket
that TCP sent UDP UDP

“byte stream”)
packet packet

client
clientSocket UDP
socket UDP
socket

to network from network

H. Fauconnier M2-Internet Java 6


Example: Java client (UDP)
import java.io.*;
import java.net.*;

class UDPClient {
public static void main(String args[]) throws Exception
{
Create
input stream BufferedReader inFromUser =
Create new BufferedReader(new InputStreamReader(System.in));
client socket
DatagramSocket clientSocket = new DatagramSocket();
Translate
hostname to IP InetAddress IPAddress = InetAddress.getByName("hostname");
address using DNS
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, DatagramPacket sendPacket =
length, IP addr, port new DatagramPacket(sendData, sendData.length, IPAddress, 9876);

Send datagram clientSocket.send(sendPacket);


to server
DatagramPacket receivePacket =
new DatagramPacket(receiveData, receiveData.length);
Read datagram
from server 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.*;

class UDPServer {
public static void main(String args[]) throws Exception
Create {
datagram socket
at port 9876 DatagramSocket serverSocket = new DatagramSocket(9876);

byte[] receiveData = new byte[1024];


byte[] sendData = new byte[1024];

while(true)
{
Create space for
received datagram DatagramPacket receivePacket =
new DatagramPacket(receiveData, receiveData.length);
Receive serverSocket.receive(receivePacket);
datagram
H. Fauconnier M2-Internet Java 9
Example: Java server (UDP), cont
String sentence = new String(receivePacket.getData());
Get IP addr
port #, of InetAddress IPAddress = receivePacket.getAddress();
sender
int port = receivePacket.getPort();

String capitalizedSentence = sentence.toUpperCase();

sendData = capitalizedSentence.getBytes();
Create datagram
to send to client DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress,
port);
Write out
datagram serverSocket.send(sendPacket);
to socket }
}
} End of while loop,
loop back and wait for
another datagram
H. Fauconnier 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 length, SocketAddress destination, int
port)

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
duplicate
R1 creation/transmission R1
duplicate
R2 R2

R3 R4 R3 R4

source in-network
duplication 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

B B
c c

D D
F E F E

G G
(a) Broadcast initiated at A (b) Broadcast initiated at D

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
3
B B
c c
4
2
D D
F E F E
1 5
G G
(a) Stepwise construction (b) Constructed spanning
of spanning tree tree
H. Fauconnier 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 M2-Internet Java 1-36
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 M2-Internet Java 1-37


Shortest Path Tree
 mcast forwarding tree: tree of shortest
path routes from source to all receivers
 Dijkstra’s algorithm

S: source LEGEND
R1 2
1 R4 router with attached
group member
R2 5
router with no attached
3 4
R5 group member
R3 6 i link used for forwarding,
R6 R7 i indicates order link
added by algorithm

H. Fauconnier M2-Internet Java 1-38


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 M2-Internet Java 1-39


Reverse Path Forwarding: example
S: source
LEGEND
R1
R4 router with attached
group member
R2
router with no attached
R5 group member
R3 datagram will be
R6 R7 forwarded
datagram will not be
forwarded

• result is a source-specific reverse SPT


– may be a bad choice with asymmetric links

H. Fauconnier M2-Internet Java 1-40


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 router with attached


R4
group member

R2 router with no attached


P group member
P
R5 prune message
R3 P links with multicast
R6 R7 forwarding

H. Fauconnier M2-Internet Java 1-41


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 M2-Internet Java 1-42


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 M2-Internet Java 1-43
Center-based trees: an example

Suppose R6 chosen as center:

LEGEND

R1 router with attached


R4
3 group member

R2 router with no attached


2 group member
1
R5 path order in which join
messages generated
R3
1 R6 R7

H. Fauconnier M2-Internet Java 1-44


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 M2-Internet Java 1-45


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 M2-Internet Java 1-46


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


addressed) 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 M2-Internet Java 1-47


PIM: Protocol Independent Multicast
 not dependent on any specific underlying unicast
routing algorithm (works with all)
 two different multicast distribution scenarios :

Dense: Sparse:
 group members densely  # networks with group members
packed, in “close” proximity. small wrt # interconnected networks
 bandwidth more plentiful  group members “widely dispersed”
 bandwidth not plentiful

H. Fauconnier M2-Internet Java 1-48


Consequences of Sparse-Dense Dichotomy:

Dense Sparse:
 group membership by  no membership until
routers assumed until routers explicitly join
routers explicitly prune  receiver- driven
 data-driven construction construction of mcast
on mcast tree (e.g., RPF) tree (e.g., center-based)
 bandwidth and non-  bandwidth and non-group-
group-router processing router processing
profligate conservative

H. Fauconnier M2-Internet Java 1-49


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 M2-Internet Java 1-50


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

H. Fauconnier M2-Internet Java 1-51


PIM - Sparse Mode
sender(s):
 unicast data to RP,
which distributes down R1
R4
RP-rooted tree join

 RP can extend mcast R2


join
tree upstream to R5
source join
R3 R7
 RP can send stop msg R6
if no attached
all data multicast rendezvous
receivers from rendezvous point
 “no one is listening!” point

H. Fauconnier M2-Internet Java 1-52


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

You might also like