Java.net.DatagramPacket.setPort() Method



Description

The java.net.DatagramPacket.setPort(int iport) sets the port number on the remote host to which this datagram is being sent.

Declaration

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

public void setPort(int iport)

Parameters

  • iport - the port number

Return Value

This method does not return any value.

Exception

  • NA

Example

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

package com.tutorialspoint;

import java.net.*;

class DatagramPacketDemo {

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

      // create a DatagramSocket object
      DatagramSocket ds = new DatagramSocket();

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

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

      // create a int object iport and assign value to it
      int iport = 9999;

      // set the port number for datagram dp
      dp.setPort(iport);

      String str = "Data being sent using port number : " + iport;

      System.out.println( str );
   }
}

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

Data being sent using port number : 9999
Advertisements