【Java】 IPアドレスからホスト名を取得

IPアドレスからホスト名を取得

 * InetAddress.getByName() / InetAddress.getLocalHost() を使用する

■ 注意

 * InetAddress.getByName("localhost") / InetAddress.getByName("127.0.0.1") / InetAddress.getLocalHost()
   で動作が異なるので、注意!!(以下のサンプルの出力結果を参照)

■ サンプル

import java.net.InetAddress;

public class Main {

  public static void main(String[] args) {
    try {
      // [1-1]
      InetAddress inetAddressForLocalhost = InetAddress.getByName("localhost");
      String ipForLocalhost = inetAddressForLocalhost.getHostAddress();
      String hostnameForLocalhost = inetAddressForLocalhost.getHostName();
      // 画面表示
      System.out.println("IPアドレス:" + ipForLocalhost);
      System.out.println("ホスト名:" + hostnameForLocalhost);

      System.out.println("");
      System.out.println("*********************************************");
      System.out.println("");

      // [1-2]
      InetAddress inetAddressFor127001 = InetAddress.getByName("127.0.0.1");
      String ipFor127001 = inetAddressFor127001.getHostAddress();
      String hostnameFor127001 = inetAddressFor127001.getHostName();
      // 画面表示
      System.out.println("IPアドレス:" + ipFor127001);
      System.out.println("ホスト名:" + hostnameFor127001);

      System.out.println("");
      System.out.println("*********************************************");
      System.out.println("");

      // [1-3]
      InetAddress inetAddressForLocalHost = InetAddress.getLocalHost();
      String ipForLocalHost = inetAddressForLocalHost.getHostAddress();
      String hostnameForLocalHost = inetAddressForLocalHost.getHostName();
      // 画面表示
      System.out.println("IPアドレス:" + ipForLocalHost);
      System.out.println("ホスト名:" + hostnameForLocalHost);
      
      System.out.println("");
      System.out.println("*********************************************");
      System.out.println("");
      
      // [2]
      InetAddress inetAddressForYahoo = InetAddress.getByName("yahoo.co.jp");
      String ipForYahoo = inetAddressForYahoo.getHostAddress();
      String hostnameForYahoo = inetAddressForYahoo.getHostName();
      // 画面表示
      System.out.println("IPアドレス:" + ipForYahoo);
      System.out.println("ホスト名:" + hostnameForYahoo);
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
}

出力結果

IPアドレス127.0.0.1
ホスト名:localhost

*********************************************

IPアドレス127.0.0.1
ホスト名:127.0.0.1

*********************************************

IPアドレス:192.XXX.XXX.XXX
ホスト名:xxxx(コンピュータ名が表示)

*********************************************

IPアドレス:182.22.XXX.XXX
ホスト名:yahoo.co.jp