Java如何从IP地址查找主机名?

时间:2020-12-12 13:33:12

在Java编程中,如何从IP地址查询出主机名?

以下示例显示了如何通过net.InetAddress类的InetAddress.getByName()方法将指定的IP地址查到主机名称。

package com.yiibai; import java.net.InetAddress; public class HostSpecificByIP { public static void main(String[] argv) throws Exception { InetAddress addr = InetAddress.getByName("www.yiibai.com"); System.out.println("Host name is: "+addr.getHostName()); System.out.println("Ip address is: "+ addr.getHostAddress()); } } 
Java

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

Host name is: www.yiibai.com
Ip address is: 112.124.103.85
Shell

示例-2

从IP地址查找主机名的另一个示例:

package com.yiibai; import java.net.InetAddress; import java.net.UnknownHostException; public class HostSpecificByIP2 { 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(); } } } 
Java

上述代码示例将产生以下结果(输出页面源代码) -

Your current IP address : YB-PC/192.168.1.50
Your current Hostname : YB-PC