Getting the Hostname of an IP Address - Java Network

Java examples for Network:IP Address

Description

Getting the Hostname of an IP Address

Demo Code

import java.net.InetAddress;
import java.net.UnknownHostException;

public class Main {
  public void m() {
    try {/*from   w w w.  j a va  2  s.  c o m*/
      // Get hostname by textual representation of IP address
      InetAddress addr = InetAddress.getByName("127.0.0.1");

      // Get hostname by a byte array containing the IP address
      byte[] ipAddr = new byte[] { 127, 0, 0, 1 };
      addr = InetAddress.getByAddress(ipAddr);

      // Get the host name
      String hostname = addr.getHostName();

      // Get canonical host name
      String hostnameCanonical = addr.getCanonicalHostName();
    } catch (UnknownHostException e) {
    }
  }
}

Related Tutorials