黑马程序员技术交流社区

标题: 通过域名获取IP地址 [打印本页]

作者: littlefoxtail    时间: 2013-5-20 16:38
标题: 通过域名获取IP地址
本帖最后由 littlefoxtail 于 2013-5-21 13:55 编辑

复制代码
  1. InetAddress[] ia=InetAddress.getAllByName("www.baidu.com");
  2.                 for(InetAddress x:ia){
  3.                 System.out.println(x.getHostAddress());
  4.                 }
复制代码
老报 java.net.UnknownHostException错误,这是哪儿的问题呢?

作者: 任江峰    时间: 2013-5-20 17:16
本帖最后由 任江峰 于 2013-5-20 17:33 编辑

需要加try,catch块。我加了以后可以运行。当然必须要联网才行。
  1. import java.net.InetAddress;
  2. import java.net.UnknownHostException;

  3. public class TestIPAddress {

  4.         public static void main(String[] args) {
  5.                 InetAddress[] ia=null;
  6.                 try {
  7.                         ia = InetAddress.getAllByName("www.baidu.com");
  8.                 } catch (UnknownHostException e) {
  9.                         e.printStackTrace();
  10.                 }
  11.                
  12.         for(InetAddress x:ia){
  13.         System.out.println(x.getHostAddress());
  14.         }
  15.         }
  16. }
  17. /*
  18. 运行结果:
  19. 220.181.111.148
  20. 220.181.112.143
  21. */
复制代码
黑马云青年为您解答。
作者: 金辉    时间: 2013-5-20 17:17
个人认为,你写成baidu这是网上的地址,要获取他的IP你的机子得联网
作者: littlefoxtail    时间: 2013-5-20 18:03
任江峰 发表于 2013-5-20 17:16
需要加try,catch块。我加了以后可以运行。当然必须要联网才行。黑马云青年为您解答。 ...

我联着网呀,你的那串代码还是报哪个错误,难道是人品问题 {:3_48:}
作者: 任江峰    时间: 2013-5-20 18:05
本帖最后由 任江峰 于 2013-5-20 18:08 编辑

用浏览器可以打开百度吗?
在cmd ping www.baidu.com可以ping通吗?
配置系统的dns为8.8.8.8再试试。

作者: SOAR    时间: 2013-5-20 18:19
得联网。




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2