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
//Java program to illustrate various
//DatagramPacket class methods
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 for sending the data
DatagramPacket dp1 = new DatagramPacket(ar, 4, ip, 1052);
// setAddress() method
// I have used same address as in initiation
dp1.setAddress(ip);
// getAddress() method
System.out.println("Address : " + dp1.getAddress());
// setPort() method
dp1.setPort(2525);
// getPort() method
System.out.println("Port : " + dp1.getPort());
// setLength() method
dp1.setLength(4);
// getLength() method
System.out.println("Length : " + dp1.getLength());
// setData() method
dp1.setData(buf);
// getData() method
System.out.println("Data : " + Arrays.toString(dp1.getData()));
// setSocketAddress() method
//dp1.setSocketAddress(address.getLocalSocketAddress());
// getSocketAddress() method
System.out.println("Socket Address : " + dp1.getSocketAddress());
// getOffset() method
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 Tutorial Java is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. It is known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Java s
10 min read
Java OOP(Object Oriented Programming) Concepts Java Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable.The core idea of OOPs is to bind data and the functions that operate on it,
13 min read
Java Interview Questions and Answers Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
Arrays in Java Arrays in Java are one of the most fundamental data structures that allow us to store multiple values of the same type in a single variable. They are useful for storing and managing collections of data. Arrays in Java are objects, which makes them work differently from arrays in C/C++ in terms of me
15+ min read
Collections in Java Any group of individual objects that are represented as a single unit is known as a Java Collection of Objects. In Java, a separate framework named the "Collection Framework" has been defined in JDK 1.2 which holds all the Java Collection Classes and Interface in it. In Java, the Collection interfac
15+ min read
Inheritance in Java Java Inheritance is a fundamental concept in OOP(Object-Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from an
13 min read
Java Exception Handling Exception handling in Java allows developers to manage runtime errors effectively by using mechanisms like try-catch block, finally block, throwing Exceptions, Custom Exception handling, etc. An Exception is an unwanted or unexpected event that occurs during the execution of a program, i.e., at runt
10 min read
Java Programs - Java Programming Examples In this article, we will learn and prepare for Interviews using Java Programming Examples. From basic Java programs like the Fibonacci series, Prime numbers, Factorial numbers, and Palindrome numbers to advanced Java programs.Java is one of the most popular programming languages today because of its
8 min read
Java Interface An Interface in Java programming language is defined as an abstract type used to specify the behaviour of a class. An interface in Java is a blueprint of a behaviour. A Java interface contains static constants and abstract methods. Key Properties of Interface:The interface in Java is a mechanism to
12 min read
Introduction to Java Java is a high-level, object-oriented programming language developed by Sun Microsystems in 1995. It is platform-independent, which means we can write code once and run it anywhere using the Java Virtual Machine (JVM). Java is mostly used for building desktop applications, web applications, Android
4 min read