Java.net.DatagramPacket.getSocketAddress() Method



Description

The java.net.DatagramPacket.getSocketAddress() gets the SocketAddress (usually IP address + port number) of the remote host that this packet is being sent to or is coming from.

Declaration

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

public SocketAddress getSocketAddress()

Parameters

  • NA

Return Value

This method returns the the SocketAddress.

Exception

  • NA

Example

The following example shows the usage of net.DatagramPacket.getSocketAddress() 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);

      String str = "Socket address is : " + dp.getSocketAddress();

      // print socket address value
      System.out.println( str );
   }
}

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

Socket address is : /127.0.0.1:1075
Advertisements