Java.net.DatagramPacket.setSocketAddress() Method



Description

The java.net.DatagramPacket.setSocketAddress(SocketAddress address) sets the SocketAddress (usually IP address + port number) of the remote host to which this datagram is being sent.

Declaration

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

public void setSocketAddress(SocketAddress address)

Parameters

  • address - the SocketAddress

Return Value

This method does not return any value.

Exception

  • IllegalArgumentException - if address is null or is a SocketAddress subclass not supported by this socket

Example

The following example shows the usage of net.DatagramPacket.setSocketAddress() 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 InetAddress object ia and assign destination address
      InetAddress ia = InetAddress.getByName("localhost");

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

      // create SocketAddress object sa and assign socket address
      SocketAddress sa = new InetSocketAddress(ia, iport);

      // set the socket address sa for datagram dp
      dp.setSocketAddress(sa);

      String str = "Data being sent to socket address : " + sa;

      System.out.println( str );
   }
}

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

Data being sent to socket address : localhost/127.0.0.1:9999
Advertisements