Java.net.DatagramPacket.getLength() Method



Description

The java.net.DatagramPacket.getLength() returns the length of the data to be sent or the length of the data received.

Declaration

Following is the declaration for java.net.DatagramPacket.getLength() method

public int getLength()

Parameters

  • NA

Return Value

This method returns the length of the data to be sent or the length of the data received.

Exception

  • NA

Example

The following example shows the usage of net.DatagramPacket.getLength() method

package com.tutorialspoint;

import java.net.*;

class DatagramPacketDemo {

   public static void main(String args[]) throws Exception {

      // create a DatagramSocket object binded to port 9999
      DatagramSocket ds = new DatagramSocket(9999);

      // create a byte array buf
      byte buf[] = new byte[100];

      // create a DatagramPacket object
      DatagramPacket dp = new DatagramPacket(buf, buf.length);

      // recieve the datagram packet into dp
      ds.receive(dp);

      // length of data received is stored in l
      int l = dp.getLength();

     // print l value
     System.out.println("Length of data received is : " + l );
   }
}

Let us compile and run the above program, this will produce the following result:

Length of data received is : 5
Advertisements