0% found this document useful (0 votes)
139 views33 pages

User Datagram Protocol

This document discusses Java's implementation of the User Datagram Protocol (UDP). It describes the two main classes used for UDP in Java - DatagramPacket and DatagramSocket. DatagramPacket represents a UDP datagram and has methods for getting/setting packet data and addresses. DatagramSocket represents a UDP socket and has methods for sending/receiving DatagramPackets and getting/setting socket properties like port numbers. The document provides examples of how to use these classes to send and receive UDP datagrams in Java applications.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
139 views33 pages

User Datagram Protocol

This document discusses Java's implementation of the User Datagram Protocol (UDP). It describes the two main classes used for UDP in Java - DatagramPacket and DatagramSocket. DatagramPacket represents a UDP datagram and has methods for getting/setting packet data and addresses. DatagramSocket represents a UDP socket and has methods for sending/receiving DatagramPackets and getting/setting socket properties like port numbers. The document provides examples of how to use these classes to send and receive UDP datagrams in Java applications.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 33

UDP

USER DATAGRAM PROTOCOL


INTRODUCTION
 Java’s implementation of UDP is split into two classes:
1. DatagramPacket and
2. DatagramSocket.
 The DatagramPacket class stuffs bytes of data into UDP packets called
datagrams and lets you unstuff datagrams that you receive.
 A DatagramSocket sends as well as receives UDP datagrams.
 To send data, put the data in a DatagramPacket and send the packet using a
DatagramSocket.
 To receive data, take a DatagramPacket object from a DatagramSocket and
then inspect the contents of the packet.
 In UDP, everything about a datagram, including the address to which it is
directed, is included in the packet itself; the socket only needs to know the
local port on which to listen or send.
Features of an UDP connection
1. UDP doesn’t have any notion of a unique connection
between two hosts. A single DatagramSocket can send data
to and receive data from many independent hosts. The
socket isn’t dedicated to a single connection.
2. Unlike TCP, UDP sockets does not treat a network
connection as a stream:
The DatagramPacket Class
 In Java, a UDP datagram is represented by an instance of
the DatagramPacket class:
public final class DatagramPacket extends Object
 This class provides methods,
 to get and set the source or destination address from the IP
header,
 to get and set the source or destination port,
 to get and set the data, and
 to get and set the length of the data.
The Constructors
 DatagramPacket uses different constructors depending on
whether the packet will be used to send data or to receive
data.
 All six constructors take as arguments a byte array that
holds the datagram’s data and the number of bytes in that
array to use for the datagram’s data.
 To receive a datagram, provide only these two arguments.
 To send a datagram, constructors require a buffer array
and a length, and it also requires an address and port to
which the packet will be sent
Constructors for receiving datagrams
public DatagramPacket(byte[] buffer, int length)
public DatagramPacket(byte[] buffer, int offset, int length)
 If you try to construct a DatagramPacket with a length that
will overflow the buffer, the constructor throws an
IllegalArgumentException.
 Most native UDP implementations don’t support more
than 8,192 bytes (8K) of data per datagram.
 In practice, however, many UDP-based protocols such as
DNS and TFTP use packets with 512 bytes of data per
datagram or fewer
Constructors for sending datagrams
 These four constructors create new DatagramPacket
objects used to send data across the network:
1. public DatagramPacket(byte[] data, int length,
InetAddress destination, int port)
2. public DatagramPacket(byte[] data, int offset, int
length, InetAddress destination, int port)
3. public DatagramPacket(byte[] data, int length,
SocketAddress destination)
4. public DatagramPacket(byte[] data, int offset, int
length, SocketAddress destination)
 It’s customary to convert the data to a byte array and place it in
data before creating the DatagramPacket.
 Example:
String s = "This is a test";
byte[] data = s.getBytes("UTF-8");
try {
InetAddress ia = InetAddress.getByName("www.ibiblio.org");
int port = 7;
DatagramPacket dp = new DatagramPacket(data, data.length, ia, port);
// send the packet...
} catch (IOException ex)
}
The get Methods
 DatagramPacket has six methods that retrieve different
parts of a datagram:
1. public InetAddress getAddress()
2. public int getPort()
3. public SocketAddress getSocketAddress()
4. public byte[] getData()
5. public int getLength()
6. public int getOffset()
Example
import java.io.*;
import java.net.*;
public class DatagramExample {
public static void main(String[] args) {
String s = "This is a test.";
try {
byte[] data = s.getBytes("UTF-8");
InetAddress ia = InetAddress.getByName("www.ibiblio.org");
int port = 7;
DatagramPacket dp = new DatagramPacket(data, data.length, ia, port);
System.out.println("This packet is addressed to "+ dp.getAddress() + " on
port " + dp.getPort());
System.out.println("There are " + dp.getLength()
+ " bytes of data in the packet");
System.out.println(
new String(dp.getData(), dp.getOffset(), dp.getLength(), "UTF-8"));
} catch (UnknownHostException | UnsupportedEncodingException ex) {
System.err.println(ex);
}
}
}
The setter Methods
1. public void setData(byte[] data)
2. public void setData(byte[] data, int offset, int length)
3. public void setAddress(InetAddress remote)
4. public void setPort(int port)
5. public void setAddress(SocketAddress remote)
6. public void setLength(int length)
Example- sending a large array in 512-byte
chunks:
int offset = 0;
DatagramPacket dp = new DatagramPacket(bigarray, offset, 512);
int bytesSent = 0;
while (bytesSent < bigarray.length) {
socket.send(dp);
bytesSent += dp.getLength();
int bytesToSend = bigarray.length - bytesSent;
int size = (bytesToSend > 512) ? 512 : bytesToSend;
dp.setData(bigarray, bytesSent, size);
}
public void setAddress(InetAddress remote)
 To send the same datagram to many different recipients
String s = "Really Important Message";
byte[] data = s.getBytes("UTF-8");
DatagramPacket dp = new DatagramPacket(data, data.length);
dp.setPort(2000);
String network = "128.238.5.";
for (int host = 1; host < 255; host++) {
try {
InetAddress remote = InetAddress.getByName(network + host);
dp.setAddress(remote);
socket.send(dp);
} catch (IOException ex) {
// skip it; continue with the next host
}
}
DatagramPacket input = new DatagramPacket(new byte[8192],
8192);
socket.receive(input);
DatagramPacket output = new DatagramPacket("Hello
there".getBytes("UTF-8"), 11);
SocketAddress address = input.getSocketAddress();
output.setAddress(address);
socket.send(output);
The DatagramSocket Class
 To send or receive a DatagramPacket, you must open a datagram socket.
 In Java, a datagram socket is created and accessed through the
DatagramSocket class:
public class DatagramSocket extends Object
 All datagram sockets bind to a local port, on which they listen for
incoming data and which they place in the header of outgoing
datagrams.
 When a server constructs a DatagramSocket, it specifies the local port
on which it will listen.
 When a Client constructs a DatagramSocket, it specifies an anonymous
(system-assigned) port number.
 One DatagramSocket can send and receive datagrams from multiple
remote hosts and ports.
The Constructors
1. public DatagramSocket() throws SocketException
 creates a socket that is bound to an anonymous port
 Example:
try {
DatagramSocket client = new DatagramSocket();
// send packets...
} catch (SocketException ex) {
System.err.println(ex);
}
2. public DatagramSocket(int port) throws
SocketException
 This constructor creates a socket that listens for incoming

datagrams on a particular port, specified by the port


argument.
 Use this constructor to write a server that listens on
a well-known port.
Example-Look for local UDP ports
 TCP ports and UDP ports are not related. Two different
programs can use the same port number if one uses UDP
and the other uses TCP.
for (int port = 1024; port <= 65535; port++) {
try {
DatagramSocket server = new DatagramSocket(port);
server.close();
} catch (SocketException ex) {
System.out.println("There is a server on port " + port + ".");
}
3. public DatagramSocket(int port, InetAddress interface)
throws SocketException
 it creates a socket that listens for incoming datagrams on a
specific port and network interface
4. public DatagramSocket(SocketAddress interface)
throws SocketException
SocketAddress address = new InetSocketAddress("127.0.0.1", 9999);
DatagramSocket socket = new DatagramSocket(address);
Sending Datagrams
 The primary task of the DatagramSocket class is to send
and receive UDP datagrams.
 One socket can both send and receive.
public void send(DatagramPacket dp) throws IOException
Example:
theSocket.send(theOutput);
Receiving datagrams
 public void receive(DatagramPacket dp) throws IOException
 This method receives a single UDP datagram from the
network and stores it in the preexisting DatagramPacket
object dp.
 Example:
 theSocket.receive(dp);
Other Methods
 public void close()
 Calling a DatagramSocket object’s close() method frees the port
occupied by that socket.
 public int getLocalPort()
 returns an int that represents the localport on which the socket
is listening.
 Example:
DatagramSocket ds = new DatagramSocket();
System.out.println("The socket is using port " +
ds.getLocalPort());
 public InetAddress getLocalAddress()
 public SocketAddress getLocalSocketAddress()
Managing Connections
 The next five methods let you choose which host you can
send datagrams to and receive datagrams from, while
rejecting all others’ packets.
1. public void connect(InetAddress host, int port)
2. public void disconnect()
3. public int getPort()
4. public InetAddress getInetAddress()
5. public InetAddress getRemoteSocketAddress()
Socket Options
 Java supports six socket options for UDP:
1. SO_TIMEOUT
2. SO_RCVBUF
3. SO_SNDBUF
4. SO_REUSEADDR
5. SO_BROADCAST
6. IP_TOS
SO_TIMEOUT
 SO_TIMEOUT is the amount of time, in milliseconds,
that receive() waits for an incoming datagram before
throwing an InterruptedIOException, which is a subclass
of IOException.
 public void setSoTimeout(int timeout) throws
SocketException
 public int getSoTimeout() throws IOException
SO_RCVBUF
 It determines the size of the buffer used for network I/O.
 SO_RCVBUF sets the maximum size of datagram packets
that can be received by the application.
 public void setReceiveBufferSize(int size) throws
SocketException
 public int getReceiveBufferSize() throws SocketException
SO_SNDBUF
 public void setSendBufferSize(int size) throws
SocketException
 public int getSendBufferSize() throws SocketException
SO_REUSEADDR
 For UDP, SO_REUSEADDR controls whether multiple
datagram sockets can bind to the same port and address at
the same time.
 If multiple sockets are bound to the same port, received
packets will be copied to all bound sockets. This option is
controlled by these two methods:
 public void setReuseAddress(boolean on) throws
SocketException
 public boolean getReuseAddress() throws SocketException
SO_BROADCAST
 The SO_BROADCAST option controls whether a socket
is allowed to send packets to and receive packets from
broadcast addresses such as 192.168.254.255 the local
network broadcast address for the network with the local
address 192.168.254.*
 public void setBroadcast(boolean on) throws SocketException
 public boolean getBroadcast() throws SocketException
IP_TOS
 public int getTrafficClass() throws SocketException
 public void setTrafficClass(int trafficClass) throws
SocketException
 The traffic class is given as an int between 0 and 255.
 Because this value is copied to an eight-bit field in the
TCP header, only the low-order byte of this int is used;
and values outside this range cause
IllegalArgumentExceptions.
 Example:
 DatagramSocket s = new DatagramSocket();
 s.setTrafficClass(0xB8); // 10111000 in binary

You might also like