如何在 Java 中通过 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.html