Java 实例 - 获取指定主机的IP地址


以下实例演示了如何使用 InetAddress 类的 InetAddress.getByName() 方法来获取指定主机(网址)的IP地址:

  1. /*
  2. author by shouce.ren
  3. GetIP.java
  4. */
  5.  
  6. import java.net.InetAddress;
  7. import java.net.UnknownHostException;
  8.  
  9. public class GetIP {
  10. public static void main(String[] args) {
  11. InetAddress address = null;
  12. try {
  13. address = InetAddress.getByName
  14. ("www.shouce.ren");
  15. }
  16. catch (UnknownHostException e) {
  17. System.exit(2);
  18. }
  19. System.out.println(address.getHostName() + "="
  20. + address.getHostAddress());
  21. System.exit(0);
  22. }
  23. }

以上代码运行输出结果为:

  1. www.shouce.ren=222.73.134.120