在Java编程中,如何根据主机名(域名)获取IP地址?
以下示例显示了如何通过net.InetAddress
类的InetAddress.getByName()
方法将主机名更改为指定的IP地址。
package com.yiibai; import java.net.InetAddress; import java.net.UnknownHostException; public class HostSpecificIPAddress { public static void main(String[] args) { InetAddress address = null; try { address = InetAddress.getByName("www.yiibai.com"); } catch (UnknownHostException e) { System.exit(2); } System.out.println(address.getHostName() + " IP is = " + address.getHostAddress()); System.exit(0); } }
上述代码示例将产生以下结果 -
www.yiibai.com IP is = 112.124.103.85
示例-2
以下是Java中使用getHostAddress()
和getHostName()
获取本机的另一个示例 -
package com.yiibai; import java.net.InetAddress; import java.net.UnknownHostException; public class HostSpecificIPAddress2 { public static void main(String[] args) { InetAddress ipadd; String hostname; try { ipadd = InetAddress.getLocalHost(); hostname = ipadd.getHostName(); System.out.println("Your IP address : " + ipadd); System.out.println("Your Hostname : " + hostname); } catch (UnknownHostException e) { } } }
上述代码示例将产生以下结果 -
Your IP address : Yiibai-PC/192.168.1.50
Your Hostname : Yiibai-PC