Java API Tutorial - Java DatagramSocket .getLocalAddress ()








Syntax

DatagramSocket.getLocalAddress() has the following syntax.

public InetAddress getLocalAddress()

Example

In the following code shows how to use DatagramSocket.getLocalAddress() method.

/*from  w w w .  j  a  va  2  s  . c o m*/
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class Main {

  public static void main(String args[]) {
    try {

      InetAddress ia = InetAddress.getByName("www.java2s.com");

      DatagramSocket ds = new DatagramSocket();

      byte buffer[] = "hello".getBytes();
      DatagramPacket dp = new DatagramPacket(buffer, buffer.length, ia, 80);

      
      // Send the datagram packet
      ds.send(dp);
      
      
      System.out.println(ds.getLocalAddress());
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
} 

The code above generates the following result.