如何从 IP 地址中找到主机名?



问题描述

如何从 IP 地址中找到主机名?

解决方案

以下示例展示了如何通过 net.InetAddress 类的 InetAddress.getByName() 方法将主机名更改为其特定 IP 地址。

import java.net.InetAddress;

public class Main {
   public static void main(String[] argv) throws Exception {
      InetAddress addr = InetAddress.getByName("74.125.67.100");
      System.out.println("Host name is: "+addr.getHostName());
      System.out.println("Ip address is: "+ addr.getHostAddress());
   }
}

结果

以上代码示例将产生以下结果。

Host name is: 100.67.125.74.bc.googleusercontent.com
Ip address is: 74.125.67.100

以下示例从 IP 地址查找主机名

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

public class NewClass1 {
   public static void main(String[] args) {
      InetAddress ip;
      String hostname;
      try {
         ip = InetAddress.getLocalHost();
         hostname = ip.getHostName();
         System.out.println("Your current IP address : " + ip);
         System.out.println("Your current Hostname : " + hostname);
      } catch (UnknownHostException e) {
         e.printStackTrace();
      }
   }
}

以上代码示例将产生以下结果。

Your current IP address : localhost/127.0.0.1
Your current Hostname : localhost
java_networking.htm
广告