Table of contents
1.
Introduction
2.
Datagrams
3.
DatagramPacket
3.1.
Constructors
3.2.
Methods
4.
DatagramSocket
4.1.
Constructors
4.2.
Methods
5.
Example
6.
Frequently Asked Questions
6.1.
What is InetAddress?
6.2.
What are two main exceptions a DatagamSocket constructor can throw?
6.3.
What is the difference between the bind and connect() methods in DatagramSocket class?
7.
Conclusion
Last Updated: Mar 27, 2024

DatagramPacket and DatagaramSocket in Java

Author Yashesvinee V
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Computer Networks deal with the connections between multiple devices to exchange data. It mainly focuses on client-server interactions via a transmission channel. Data is transferred in the form of packets to endpoints knowns as sockets. Data packets are sent and received via these sockets, a type of Application Programming Interfaces (APIs). Socket programming defines ways of connecting two nodes in a network for communication. One socket listens on a particular port at an IP address, while the other reaches out to it to form a connection and exchange packets. 

Must Read, Multithreading in java and Hashcode Method in Java

Datagrams

A datagram is an independent, self-contained message sent over the network whose arrival, arrival time, and content are not guaranteed. Applications that communicate via datagrams send and receive packets of information. The java.net package contains the classes to use the concept of datagrams to transmit packets over the network. In simple terms, datagrams are bundles of information passed between machines. Once the datagram has been sent, there is no guarantee that it will reach or be received successfully.

Java implements datagrams on UDP (User Datagram Protocol) with the help of two classes.

  1. DatagramPacket class whose object is the data container.
     
  2. DatagramSocket class provides the mechanism to send or receive DatagramPacket objects.

DatagramPacket

Datagram packets help implement a connectionless packet delivery service using UDP. Each message is transmitted from one machine to another based solely on data contained within that packet. Packets may or may not be delivered. The DatagramPacket class allows connecting two systems for data transfer using Java. It provides mechanisms for the creation of datagram packets for connectionless delivery. 

Syntax:

DatagramPacket dp = DatagramPacket(byte[] buf, int length).
You can also try this code with Online Java Compiler
Run Code

 

Following are some of the parameters that are used in the creation of DatagramPacket objects. 

  1. buf: The actual message to be delivered or received. The data prepared for transmission is stuffed in a byte array. It stores the message to be sent as well as the received message.
     
  2. offset: It represents the packet data offset.
     
  3. length: It is the size of the packet received. This value must be less than or equal to the size of the buffer array to prevent overflow.
     
  4. InetAddress address: It represents the destination to which the message is to be delivered.
     
  5. port: The port to which the message would be delivered.
     
  6. SocketAddress address: Information about the address and port are represented with the help of a socket address.

Constructors

Constructor

Description

DatagramPacket(byte[] buf, int length) It constructs a DatagramPacket to receive packets of a given length.
DatagramPacket(byte[] buf, int offset, int length) It constructs a DatagramPacket to receive packets of a given length with an offset.
DatagramPacket(byte buf[], int length, InetAddress address, int port) It constructs a DatagramPacket to send packets of a given length to the specified port and address.
DatagramPacket(byte buf[], int offset,  int length, SocketAddress addr) It constructs a DatagramPacket to send packets of a given length with offset to the specified socket address.
DatagramPacket(byte buf[], int offset,  int length, InetAddress addr, int port) It constructs a DatagramPacket to send packets of a given length to the specified port and address.
DatagramPacket(byte buf[], int length, SocketAddress addr) It constructs a DatagramPacket to send packets of a given length to the specified socket address.

 

Methods

Methods

Description

getAddress() It returns the system's IP address to which this datagram was sent or received.
getData() It returns the contents of the data buffer.
getLength() It returns the length of the data transmitted.
getOffset() It returns the offset of the transmitted data.
getPort() It returns the port number of the remote system from which this datagram was sent or received.
getSocketAddress() It returns the socket address of the remote system to which this datagram was sent or received.
setSocketAddress(SocketAddress addr) It sets the socket address of the system to which this datagram will be sent.
setAddress(InetAddress addr) It sets the IP address of the system to which this datagram will be sent.
setData(byte[] buf) It sets the data buffer contents to be sent.
setData(byte[] buf, int offset, int length)
setLength(int l) It sets the length of the data to be sent.
setPort(int port) It sets the port number of the system to which this datagram is to be sent.

 

DatagramSocket

A datagram socket serves as the sending or receiving point for a transmitted packet. Each packet sent or received on a socket is individually routed. A Datagram socket is a type of network socket that provides a connectionless endpoint for datagram packets. DatagramSockets is a class in Java that provides the facility to implement such sockets for network communication via UDP. Newly constructed DatagramSockets can allow the transmission of broadcast datagrams that are bound to a wildcard address. In some implementations, broadcast packets may also be received when a DatagramSocket is bound to a specific address.

Syntax:

DatagramSocket ds = DatagramSocket();
You can also try this code with Online Java Compiler
Run Code

Constructors

Constructor

Description

DatagramSocket() It constructs a datagram socket and binds it to any available and unused port on the host machine.
DatagramSocket(int port) It constructs a datagram socket and binds it to a specified port on the host machine.
DatagramSocket(int port, int, InetAddress) It constructs a datagram socket and binds it to a specified port and address on the host machine.
DatagramSocket(SocketAddress address) It constructs a datagram socket and binds it to a specified socket address on the host machine.

 

Methods

Methods

Description

bind(SocketAddress addr) It binds the DatagramSocket to a specific socket address.
close() It closes the DatagramSocket.
connect(InetAddress addr, int port) It connects the socket to a remote address and port.
connect(SocketAddress addr) It connects the socket to a remote socket address.
disconnect() It disconnects the socket.
getPort() It returns the port number to which the socket is connected.
getInetAddress() It returns the address to which the socket is connected.
getBroadcast() It checks if the broadcast is enabled.
getChannel() It returns the DatagramChannel associated with the socket, if any.
getLocalAddress() It returns the local address to which the socket is connected.
getRemoteSocketAddress() It returns the address of the endpoint connected to the socket.
getTrafficClass() It returns the type of service or traffic class in the IP datagram header for packets sent from the DatagramSocket.
isBound() It checks if the socket is bound or not.
isClosed() It checks if the socket is closed or not.
isConnected() It checks if the socket is connected or not.
receive(DatagramPacket p) It receives a packet from the socket.
send(DatagramPacket p) It sends a packet from the socket.

 

Example

Below are two programs to implement a simple interaction between a client and server program using UDP. First, the server program is run, followed by the client program. Both the programs have to run simultaneously. Enter a string at the client execution console and observe the server program’s execution console to receive the output. The server gets the string data sent from the client program and returns the string in uppercase back to the client. Both the programs involve the process of sending and receiving a DatagramPacket object via a DatagramSocket object.

Java Program for Client side:

import java.io.*; 
import java.net.*; 
import java.net.InetAddress; 
class ClientDG 
{ 
  public static void main(String[] args)throws Exception 
  { 
    BufferedReader inFromUser=new BufferedReader(new InputStreamReader(System.in)); 

    // DatagramSocket object creation
    DatagramSocket clientSocket=new DatagramSocket(); 

    InetAddress IPAddress=InetAddress.getByName("localhost"); 

    byte[] sendData=new byte[1024]; 
    byte[] receiveData=new byte[1024]; 

    System.out.println("Enter the sting"); 
    String sentence=inFromUser.readLine(); 

    sendData=sentence.getBytes(); 

    // DatagramPacket object creation    
    DatagramPacket sendPacket=new DatagramPacket(sendData,sendData.length,IPAddress,9877); 

    // Sending DatagramPacket via DatagramSocket
    clientSocket.send(sendPacket); 

    // DatagramPacket object creation
    DatagramPacket receivePacket=new DatagramPacket(receiveData,receiveData.length); 

    // Receiving DatagramPacket via DatagramSocket 
    clientSocket.receive(receivePacket); 

    String modifiedSentence=new String(receivePacket.getData()); 

    System.out.println("From SERVER in upper case:"+modifiedSentence); 

    clientSocket.close(); 
  } 
}
You can also try this code with Online Java Compiler
Run Code

 

Java Program for Server side:

import java.net.*; 
import java.net.InetAddress; 
class ServerDG 
{ 
  public static void main(String args[])throws Exception 
  { 
    // DatagramSocket object creation
    DatagramSocket serverSocket = new DatagramSocket(9877); 
    byte[] receiveData=new byte[1024]; 
    byte[] sendData=new byte[1024]; 
    while(true) 
    { 
      System.out.println("Server is up and running"); 

      // DatagramPacket object creation
      DatagramPacket receivePacket=new DatagramPacket(receiveData,receiveData.length); 

      // Receiving DatagramPacket via DatagramSocket        
      serverSocket.receive(receivePacket); 

      String sentence=new String(receivePacket.getData()); 

      System.out.println("RECEIVED:"+sentence); 

      InetAddress IPAddress=receivePacket.getAddress(); 

      int port=receivePacket.getPort(); 

      String capitalizedSentence=sentence.toUpperCase(); 
      sendData=capitalizedSentence.getBytes(); 

      // DatagramPacket object creation
      DatagramPacket sendPacket=new DatagramPacket(sendData,sendData.length,IPAddress,port); 
      
      // Sending DatagramPacket via DatagramSocket
      serverSocket.send(sendPacket); 
    } 
  } 
}
You can also try this code with Online Java Compiler
Run Code

 

Output at the server console:

Server is up and running
RECEIVED: hello

 

Output at client console:

Enter the string 
hello
From SERVER in upper case: HELLO


Try it on online java compiler.

Frequently Asked Questions

What is InetAddress?

The InetAddress class from the java.net package provides methods to obtain the IP address of any hostname. The IP address is represented by 32-bit or 128-bit unsigned number. InetAddress can handle IPv4 and IPv6 addresses. It can contain the numerical IP address and its domain name.

What are two main exceptions a DatagamSocket constructor can throw?

SocketException is thrown when the socket could not be opened, bound to the specified local port. SecurityException is thrown when a security manager exists not to allow an operation.

What is the difference between the bind and connect() methods in DatagramSocket class?

The bind() method is used to bind a socket to a particular port and "listen" for connections. The connect() method is used to open a connection to a socket already listening on a particular port.

Conclusion

This article has extensively discussed the DatagramPacket and DatagramSocket classes in Java. It covers all the constructors and methods of each class and demonstrates examples for better understanding.

Feeling curious? Coding Ninjas has you covered. Check out our articles on Introduction to Java NetworkingSocket Programming and Java URL. Follow our Guided path for Java Networking here.

Recommended Reading:

Difference Between IOT and M2M

Explore our Library on Coding Ninjas Studio to gain knowledge on Data Structures and AlgorithmsMachine LearningDeep Learning, and many more! Test your coding skills by solving our test series and participating in the contests hosted on Coding Ninjas Studio! 

Looking for questions from tech giants like Amazon, Microsoft, Uber, etc.? Look at the problems, interview experiences, and interview bundle for placement preparations. Upvote our blogs if you find them insightful and engaging! Happy Coding!

Live masterclass