日期:2014-05-20  浏览次数:20659 次

关于java ping程序统计发送包的成功率

我需要一个ping 网络设备的JAVA程序 就象在dos 下ping 网络设备一样, 可以知道发了多少包,接受了多少包的程序. 

我现在写了一个这样的程序 
package com; 

import java.io.BufferedReader; 
import java.io.InputStreamReader; 
class ICMP 

/** 
  * ping 的一种实现,调用操作系统的ping命令 
  */ 
public static int ping(String host) { 
  String system = (String) (System.getProperty("os.name")).toLowerCase(); 
  String command = ""; 
  if (system.indexOf("win") != -1) { 
  command += "ping -n 5 " + host;//可以设置ping 的次数 
  } else if (system.indexOf("linux") != -1) { 
  command += "ping -t 4 " + host; //ping 四次 
  } else { 
  command += "ping " + host; 
  } 
  int minTime = Integer.MAX_VALUE, curTime; 
  try { 
  Process process = Runtime.getRuntime().exec("ping " + host); 
  BufferedReader in = new BufferedReader(new InputStreamReader( 
  process.getInputStream())); 
  String line = null; 
  int count = 10, index; 
  //最多只读10行 
  while ((line = in.readLine()) != null && count-- != 0) { 
  line = line.toLowerCase(); 
  if ((index = line.indexOf("time")) != -1) { 
  byte[] buf = line.getBytes(); 
  int start = 0, end = buf.length, i, j; 
  for (i = index + 4; i < buf.length; i++) { 
  if (Character.isDigit((char) buf[i])) { 
  start = i; 
  break; 
  } 
  } 
  if (i == buf.length) 
  continue; 
  for (j = start; j < buf.length; j++) { 
  if (Character.isLetter((char) buf[j])) { 
  end = j; 
  break; 
  } 
  } 
  curTime = Integer.parseInt(new String(buf, start, end 
  - start)); 
  if (curTime < minTime) { 
  minTime = curTime; 
  } 
  } 
  } 
  } catch (Exception ex) { 
  return Integer.MAX_VALUE; 
  } 
  return minTime; 

public static void main(String args[]) { 
ICMP ic=new ICMP(); 
System.out.println(ic.ping("10.64.2.7")); 




我想能否通过 in.readLine() 读取的信息的次数来判断到底接受几个包. 
但是 感觉好象接受的不对 , 不知道这种想法对不对,如果可行 哪位朋友可以帮忙调试一下 改一下 . 

如果有其他方法 或者类 也行. 
希望可以把问题解决 .谢谢 也希望感兴趣的朋友可以从中学习到知识 呵呵.

------解决方案--------------------
我怎么看哪都有你的这个帖
------解决方案--------------------
可以使用正则表达式分析 ping 命令的执行结果。