以下示例显示了如何借助 net.InetAddress 类的 InetAddress.getByName() 方法将主机名更改为其特定的 IP 地址。
importjava.net.InetAddress;publicclassMain{publicstaticvoidmain(String[] argv)throwsException{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 地址查找主机名的示例
importjava.net.InetAddress;importjava.net.UnknownHostException;publicclassNewClass1{publicstaticvoidmain(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.1Your current Hostname: localhost