Java.net.DatagramPacket class in Java
Last Updated :
15 Dec, 2021
This class provides facility for connection less transfer of messages from one system to another. Each message is routed only on the basis of information contained within the packet and it may be possible for different packets to route differently. There is also no guarantee as to whether the message will be delivered or not, and they may also arrive out of order. This class provides mechanisms for creation of datagram packets for connectionless delivery using datagram socket class.
Constructors : The constructors vary according to their use, i.e. for receiving or for sending the packet. The important parameters used in these constructors are-
- buf : This is the actual message that is to be delivered or received. Datagram packets receive or send data in stuffed in a byte array. If this is used in constructor for sending the message, than this represents the message to be delivered, when used for receiving purpose, it represents the buffer where the received message will be stored.
- offset : It represents the offset into the buffer array.
- length : It is the actual size of packet to receive. This must be less than or equal to the size of buffer array or else there will be overflow as received message wont fit into the array.
- InetAddress address : This is the destination to which the message is to be delivered.
- port : This is the port to which the message will be delivered.
- SocketAddress address : The information about the address and port can be represented with the help of socket address. Same function as the above two combined.
For sending purpose, following constructors are used :
Syntax :public DatagramPacket(byte[] buf,
int offset,
int length,
InetAddress address,
int port)
Parameters :
buf : byte array
offset : offset into the array
length : length of message to deliver
address : address of destination
port : port number of destination
Syntax :public DatagramPacket(byte[] buf,
int offset,
int length,
SocketAddress address)
Parameters :
buf : byte array
offset : offset into the array
length : length of message to deliver
address : socket address of destination
Syntax :public DatagramPacket(byte[] buf,
int length,
InetAddress address,
int port)
Parameters :
buf : byte array
length : length of message to deliver
address : address of destination
port : port number of destination
Syntax :public DatagramPacket(byte[] buf,
int length,
SocketAddress address)
Parameters :
buf : byte array
length : length of message to deliver
address : socket address of destination
For receiving purpose, following constructors are used :
Syntax :public DatagramPacket(byte[] buf,
int offset,
int length)
Parameters :
buf : byte array
offset : offset into the array
length : length of message to deliver
Syntax :public DatagramPacket(byte[] buf,
int length)
Parameters :
buf : byte array
length : length of message to deliver
Methods :
- getAddress() : Returns the IP address to which this packet is sent to or from which it was received.
Syntax :public InetAddress getAddress()
- getPort() : Returns the port to which this packet is sent to or from which it was received. This method is specifically used on the server from getting the port of the client who sent the request.
Syntax : public int getPort()
- getData() : Returns the data contained in this packet as a byte array. The data starts from the offset specified and is of length specified.
Syntax : public byte[] getData()
- getOffset() : Returns the offset specified.
Syntax : public int getOffset()
- getLength() : Returns the length of the data to send or receive
Syntax : public int getLength()
- setData() : Used to set the data of this packet.
Syntax : public void setData(byte[] buf,
int offset,
int length)
Parameters :
buf : data buffer
offset :offset into the data
length : length of the data
Syntax : public void setData(byte[] buf)
Parameters :
buf : data buffer
- setAddress() : Used to set the address to which this packet is sent.
Syntax : public void setAddress(InetAddress iaddr)
Parameters :
iaddr : InetAddress of the recipient
- setPort() : Set the port on which destination will receive this packet.
Syntax :public void setPort(int iport)
Parameters :
iport : the port number
- setSocketAddress() : Used to set the socket address of the destination(IP address+ port number).
Syntax : public void setSocketAddress(SocketAddress address)
Parameters :
address : socket address
- getSocketAddress() : Returns the socket address of this packet. In case it was received, return the socket address of the host machine.
Syntax : public SocketAddress getSocketAddress()
- setLength() : Used to set the length for this packet.
Syntax :public void setLength(int length)
Parameters :
length : length of the packet
Java Implementation :
Java
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.util.Arrays;
public class datapacket
{
public static void main(String[] args) throws IOException
{
byte ar[] = { 12 , 13 , 15 , 16 };
byte buf[] = { 15 , 16 , 17 , 18 , 19 };
InetAddress ip = InetAddress.getByName("localhost");
DatagramPacket dp1 = new DatagramPacket(ar, 4 , ip, 1052 );
dp1.setAddress(ip);
System.out.println("Address : " + dp1.getAddress());
dp1.setPort( 2525 );
System.out.println("Port : " + dp1.getPort());
dp1.setLength( 4 );
System.out.println("Length : " + dp1.getLength());
dp1.setData(buf);
System.out.println("Data : " + Arrays.toString(dp1.getData()));
System.out.println("Socket Address : " + dp1.getSocketAddress());
System.out.println("Offset : " + dp1.getOffset());
}
}
|
Output :
Address : localhost/127.0.0.1
Port : 2525
Length : 4
Data : [15, 16, 17, 18, 19]
Socket Address : localhost/127.0.0.1:2525
Offset : 0
For a detailed implementation of a client-server program that uses datagram socket to send the actual packets over the network, please refer to – Working with UDP Datagram Sockets
References :
Official Java Documentation
Similar Reads
Java.net.DatagramSocket class in Java
Datagram socket is a type of network socket which provides connection-less point for sending and receiving packets. Every packet sent from a datagram socket is individually routed and delivered. It can also be used for sending and receiving broadcast messages. Datagram Sockets is the java's mechanis
9 min read
Java.lang.Class class in Java | Set 1
Java provides a class with name Class in java.lang package. Instances of the class Class represent classes and interfaces in a running Java application. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects. It
15+ min read
Datagrams in Java
TCP/IP-style networking provides a serialized, predictable, reliable stream of packet data. This is not without its cost, however. TCP includes algorithms for dealing with congestion control on crowded networks, as well as pessimistic expectations about packet loss. This leads to inefficient way to
7 min read
Bytes Class | Guava | Java
Bytes is a utility class for primitive type byte. It provides Static utility methods pertaining to byte primitives, that are not already found in either Byte or Arrays and interpret bytes as neither signed nor unsigned. The methods which specifically treat bytes as signed or unsigned are found in Si
3 min read
How to run java class file which is in different directory?
In this article, we will learn about how to use other project's utilities, classes, and members. Before proceeding let's learn about some keywords. classpath Classpath is the location from where JVM starts execution of a program. Similar to the classic dynamic loading behavior, when executing Java p
6 min read
DoubleStream boxed() in Java with Examples
DoubleStream boxed() returns a Stream consisting of the elements of this stream, each boxed to a Double. Note : DoubleStream boxed() is a intermediate operation. These operations are always lazy. Intermediate operations are invoked on a Stream instance and after they finish their processing, they gi
2 min read
Collections.nCopies() in Java
The Collections.nCopies() method in Java is used to create an immutable list which contains multiple copies of the same object. This method is helpful if we want to initialize a list with n copies of given object. The newly allocated data object is tiny, i.e, it contains a single reference to the da
3 min read
Multiset Interface | Guava | Java
Introduction : Multiset is a collection that supports order-independent equality, like Set, but may have duplicate elements. We might think that a Multiset is a List then, but it is not so. Lists can hold duplicates of the same object, and Lists are always ordered. Sets can't hold duplicates, and th
5 min read
Java.util.Bitset class | Logical operations
Bitset class also allows some of the logical operations on two Bitsets. The logical operations supported are : and, andNot, or, Xor. These are discussed in this article. 1. and(Bitset set) : This method performs a logical AND of this target bit set with the argument bit set and returns the values of
5 min read
LongStream boxed() in Java
LongStream boxed() returns a Stream consisting of the elements of this stream, each boxed to a Long. Note : LongStream boxed() is a intermediate operation. These operations are always lazy. Intermediate operations are invoked on a Stream instance and after they finish their processing, they give a S
2 min read