加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

JAVA中PING IP地址的两种方法

(2013-08-07 15:55:58)
标签:

pingip

ping

ip

java

it

分类: 我的IT

        今天进行IP巡检时用到了PING IP地址,以获取该IP址是否可用,查了一些文档后,发现了两种PING的方法,但试用后,还是发现第一种比较好用,如果在局域网内,当然,第二种更有效率: 上面上代码

 

   
  // 方法一 最常用的 PING 方法
  Runtime runtime = Runtime.getRuntime(); // 获取当前程序的运行进对象
  Process process = null; // 声明处理类对象
  String line = null; // 返回行信息
  InputStream is = null; // 输入流
  InputStreamReader isr = null; // 字节流
  BufferedReader br = null;
  String ip = "www.baidu.com";
  boolean res = false;// 结果
  try {
   process = runtime.exec("ping " + ip); // PING

   is = process.getInputStream(); // 实例化输入流
   isr = new InputStreamReader(is);// 把输入流转换成字节流
   br = new BufferedReader(isr);// 从字节中读取文本
   while ((line = br.readLine()) != null) {
    if (line.contains("TTL")) {
     res = true;
     break;
    }
   }
   is.close();
   isr.close();
   br.close();
   if (res) {
    System.out.println("ping 通  ...");

   } else {
    System.out.println("ping 不通...");
   }
  } catch (IOException e) {
   System.out.println(e);
   runtime.exit(1);
  }
  //方法二 下面代码为 JDK1.5 PING的新方法但不能用,因为 该PING请求端口为7 而大型网站会关闭不需要的端口防止入侵
  InetAddress address;
  try {
   address = InetAddress.getByName("www.weibo.com");
   System.out.println("Name: " + address.getHostName());
   System.out.println("Addr: " + address.getHostAddress());
   System.out.println("Reach: " + address.isReachable(3000)); // 是否能通信 返回true或false
   System.out.println(address.toString());
  } catch (Exception e) {
   e.printStackTrace();
  }

 

                                         -----------------     抟摇直上 2013年8月7日

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有