Java.net.DatagramPacket.getAddress() Method



Description

The java.net.DatagramPacket.getAddress() returns the IP address of the machine to which this datagram is being sent or from which the datagram was received.

Declaration

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

public InetAddress getAddress()

Parameters

  • NA

Return Value

This method returns the IP address of the machine to which this datagram is being sent or from which the datagram was received.

Exception

  • NA

Example

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

      // create a InetAddress object ia, which stores the address
      InetAddress ia = dp.getAddress();

      // print ia value
      System.out.println("Address of sender is " + ia );
   }
}

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

Address of sender is /127.0.0.1
Advertisements